forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
131 lines (113 loc) · 2.23 KB
/
conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package nbio
import (
"net"
"runtime"
"time"
"unsafe"
"github.com/lesismal/nbio/logging"
)
// OnData registers callback for data.
func (c *Conn) OnData(h func(conn *Conn, data []byte)) {
c.DataHandler = h
}
// Dial wraps net.Dial.
func Dial(network string, address string) (*Conn, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
return NBConn(conn)
}
// DialTimeout wraps net.DialTimeout.
func DialTimeout(network string, address string, timeout time.Duration) (*Conn, error) {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return nil, err
}
return NBConn(conn)
}
// Lock .
func (c *Conn) Lock() {
c.mux.Lock()
}
// Unlock .
func (c *Conn) Unlock() {
c.mux.Unlock()
}
// IsClosed .
func (c *Conn) IsClosed() (bool, error) {
return c.closed, c.closeErr
}
// ExecuteLen .
func (c *Conn) ExecuteLen() int {
c.mux.Lock()
n := len(c.execList)
c.mux.Unlock()
return n
}
// Execute .
func (c *Conn) Execute(f func()) bool {
c.mux.Lock()
if c.closed {
c.mux.Unlock()
return false
}
isHead := (len(c.execList) == 0)
c.execList = append(c.execList, f)
c.mux.Unlock()
if isHead {
c.g.Execute(func() {
i := 0
for {
func() {
defer func() {
if err := recover(); err != nil {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
logging.Error("conn execute failed: %v\n%v\n", err, *(*string)(unsafe.Pointer(&buf)))
}
}()
f()
}()
c.mux.Lock()
i++
if len(c.execList) == i {
c.execList = c.execList[0:0]
c.mux.Unlock()
return
}
f = c.execList[i]
c.mux.Unlock()
}
})
}
return true
}
// MustExecute .
func (c *Conn) MustExecute(f func()) {
c.mux.Lock()
isHead := (len(c.execList) == 0)
c.execList = append(c.execList, f)
c.mux.Unlock()
if isHead {
c.g.Execute(func() {
i := 0
for {
f()
c.mux.Lock()
i++
if len(c.execList) == i {
c.execList = c.execList[0:0]
c.mux.Unlock()
return
}
f = c.execList[i]
c.mux.Unlock()
}
})
}
}