-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
254 lines (216 loc) · 4.26 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package wytcp
import (
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
)
const (
ErrorTypeUnknown = 0
ErrorTypeSendFailed = -1
ErrorTypeHandleFailed = -2
ErrorTypeWriteFailed = -3
)
var (
ErrConnClosed = errors.New("conn closed")
ErrWriteBlocking = errors.New("write blocking")
ErrReadBlocking = errors.New("read blocking")
)
type Conn struct {
server *Server
RawConn *net.TCPConn
SendCount int64 // how many package sent during this connect
ReceiveCount int64 // how many package received during this connect
sendChan chan DataPkg
receiveChan chan DataPkg
closeChan chan bool
closeOnce sync.Once
closeFlag int32
hbRequireItv time.Duration
userData interface{}
}
type Callback interface {
Connect(*Conn) bool
Close(*Conn)
Receive(*Conn, DataPkg) bool
Error(*Conn, DataPkg, int)
}
type Receiver interface {
Deserialization(*Conn) (DataPkg, error)
}
type DataPkg interface {
Serialize() []byte
}
func joinConn(conn *net.TCPConn, server *Server) {
c := &Conn{
server: server,
RawConn: conn,
SendCount: 0,
ReceiveCount: 0,
sendChan: make(chan DataPkg, server.cfg.SendChanSize),
receiveChan: make(chan DataPkg, server.cfg.ReceiveChanSize),
closeChan: make(chan bool),
hbRequireItv: server.cfg.HeartBeatCheckItv,
}
go func() {
if c.server.callback.Connect(c) {
go c.handleLoop()
go c.receiveLoop()
go c.sendLoop()
}
}()
}
func (c *Conn) Close() {
c.closeOnce.Do(func() {
atomic.StoreInt32(&c.closeFlag, 1)
close(c.closeChan)
close(c.sendChan)
close(c.receiveChan)
c.RawConn.Close()
c.server.callback.Close(c)
})
}
func (c *Conn) IsClosed() bool {
return atomic.LoadInt32(&c.closeFlag) == 1
}
func (c *Conn) receiveLoop() {
defer func() {
if e := recover(); e != nil {
runtimeError(e)
}
c.Close()
}()
for {
select {
case <-c.server.exitChan:
return
case <-c.closeChan:
return
default:
}
d, err := c.server.receiver.Deserialization(c)
if c.hbRequireItv > 0 {
msg := make(chan bool)
go heartBeating(c.RawConn, msg, c.hbRequireItv)
go gravelChannel(msg)
}
if err != nil {
return
}
c.receiveChan <- d
c.ReceiveCount++
}
}
func heartBeating(conn net.Conn, readerChannel chan bool, timeout time.Duration) {
select {
case fk := <-readerChannel:
if fk {
conn.SetDeadline(time.Now().Add(timeout))
}
break
case <-time.After(time.Second * 5):
conn.Close()
}
}
func gravelChannel(mess chan bool) {
mess <- true
close(mess)
}
func (c *Conn) SetMinHeartBeatTime(duration time.Duration) {
c.hbRequireItv = duration
}
func (c *Conn) handleLoop() {
defer func() {
if e := recover(); e != nil {
runtimeError(e)
}
c.Close()
}()
for {
select {
case <-c.server.exitChan:
return
case <-c.closeChan:
return
case d := <-c.receiveChan:
if c.IsClosed() {
c.server.callback.Error(c, d, ErrorTypeHandleFailed)
return
}
if !c.server.callback.Receive(c, d) {
return
}
}
}
}
func (c *Conn) sendLoop() {
defer func() {
if e := recover(); e != nil {
runtimeError(e)
}
c.Close()
}()
for {
select {
case <-c.server.exitChan:
return
case <-c.closeChan:
return
case d := <-c.sendChan:
if c.IsClosed() {
c.server.callback.Error(c, d, ErrorTypeSendFailed)
return
}
if _, err := c.RawConn.Write(d.Serialize()); err != nil {
return
}
c.SendCount++
}
}
}
func (c *Conn) Write(d DataPkg, timeout time.Duration) error {
var err error
defer func() {
if re := recover(); re != nil {
runtimeError(err)
}
err = ErrConnClosed
}()
if c.IsClosed() {
c.server.callback.Error(c, d, ErrorTypeWriteFailed)
return ErrConnClosed
}
if timeout == 0 {
select {
case c.sendChan <- d:
return nil
default:
return ErrWriteBlocking
}
} else {
select {
case c.sendChan <- d:
return nil
case <-c.closeChan:
return ErrConnClosed
case <-time.After(timeout):
return ErrWriteBlocking
}
}
}
func runtimeError(e interface{}) {
fmt.Println("[wytcp] error:", e)
}
func (c *Conn) RemoteAddr() net.Addr {
return c.RawConn.RemoteAddr()
}
// SetUserData set user data
func (c *Conn) SetUserData(i interface{}) {
c.userData = i
}
// GetUserData get user data
func (c *Conn) GetUserData() interface{} {
return c.userData
}