forked from Baiguoshuai1/shadiaosocketio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.go
422 lines (354 loc) · 8.54 KB
/
channel.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package shadiaosocketio
import (
"encoding/json"
"errors"
"fmt"
"github.com/Baiguoshuai1/shadiaosocketio/protocol"
"github.com/Baiguoshuai1/shadiaosocketio/utils"
"github.com/Baiguoshuai1/shadiaosocketio/websocket"
gorillaws "github.com/gorilla/websocket"
"net"
"net/http"
"strings"
"sync/atomic"
"time"
)
const (
queueBufferSize = 10000
)
const (
DefaultCloseTxt = "transport close"
DefaultCloseCode = 101
)
var (
ErrorWrongHeader = errors.New("Wrong header")
)
/*
*
engine.io header to send or receive
*/
type Header struct {
Sid string `json:"sid"`
Upgrades []string `json:"upgrades"`
PingInterval int `json:"pingInterval"`
PingTimeout int `json:"pingTimeout"`
}
const (
ChannelStateConnecting = iota
ChannelStateConnected
ChannelStateClosing
ChannelStateClosed
)
/*
*
socket.io connection handler
use IsConnected to check that handler is still working
use Dial to connect to websocket
use In and Out channels for message exchange
Close message means channel is closed
ping is automatic
*/
type Channel struct {
Backoff func(int) time.Duration
conn *websocket.Connection
out chan interface{}
header Header
state atomic.Uint32
ack ackProcessor
server *Server
ip string
request *http.Request
pingChan chan bool
}
func (c *Channel) BinaryMessage() bool {
return c.conn.GetUseBinaryMessage()
}
func (c *Channel) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *Channel) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *Channel) initChannel() {
c.pingChan = make(chan bool, 1)
c.out = make(chan interface{}, queueBufferSize)
c.state.Store(ChannelStateConnecting)
}
func (c *Channel) Id() string {
return c.header.Sid
}
func (c *Channel) ReadBytes() int {
return c.conn.GetReadBytes()
}
func (c *Channel) WriteBytes() int {
return c.conn.GetWriteBytes()
}
func (c *Channel) IsConnected() bool {
return c.state.Load() == ChannelStateConnected
}
var staticDelay = []time.Duration{
2 * time.Second,
8 * time.Second,
16 * time.Second,
32 * time.Second,
}
func reconnectChannel(c *Channel, m *methods) error {
if !(c.state.Load() == ChannelStateConnected) {
return nil
}
c.state.Store(ChannelStateConnecting)
retry := 0
for {
if c.state.Load() >= ChannelStateConnected {
return nil
}
var delay time.Duration
if c.Backoff != nil {
delay = c.Backoff(retry)
} else {
if retry >= len(staticDelay) {
delay = staticDelay[len(staticDelay)-1]
} else {
delay = staticDelay[retry]
}
}
time.Sleep(delay)
if c.state.Load() >= ChannelStateConnected {
return nil
}
utils.Debug(fmt.Sprintf("[reconnect retry] attempt %d", retry+1))
err := c.conn.Reconnect()
if err != nil {
if errors.Is(err, websocket.ReconnectNotSupported) {
return err
}
retry++
continue
}
break
}
m.callLoopEvent(c, OnReconnection)
return nil
}
/*
*
Close channel
*/
func closeChannel(c *Channel, m *methods, args ...interface{}) error {
if c.state.Load() >= ChannelStateClosing {
return nil
}
c.state.Store(ChannelStateClosing)
var s []interface{}
closeErr := &websocket.CloseError{}
if len(args) == 0 {
closeErr.Code = DefaultCloseCode
closeErr.Text = DefaultCloseTxt
s = append(s, closeErr)
} else {
s = append(s, args...)
}
c.conn.Close()
//clean outloop
for len(c.out) > 0 {
<-c.out
}
c.state.Store(ChannelStateClosed)
m.callLoopEvent(c, OnDisconnection, s...)
return nil
}
// incoming messages loop, puts incoming messages to In channel
func inLoop(c *Channel, m *methods) error {
for {
if c.state.Load() != ChannelStateConnected {
// prevents too many reads from the failed socket panic during reconnect
time.Sleep(200 * time.Millisecond)
}
msg, err := c.conn.GetMessage()
if err != nil {
err := handleReadError(err, c, m)
if err != nil {
return closeChannel(c, m, err)
}
continue
}
prefix := string(msg[0])
protocolV := c.conn.GetProtocol()
switch prefix {
case protocol.OpenMsg:
if err := utils.Json.UnmarshalFromString(msg[1:], &c.header); err != nil {
closeErr := &websocket.CloseError{}
closeErr.Code = websocket.ParseOpenMsgCode
closeErr.Text = err.Error()
return closeChannel(c, m, closeErr)
}
if protocolV == protocol.Protocol3 {
c.state.Store(ChannelStateConnected)
m.callLoopEvent(c, OnConnection)
// in protocol v3, the client sends a ping, and the server answers with a pong
go SchedulePing(c)
}
if c.conn.GetProtocol() == protocol.Protocol4 {
params := make(map[string]interface{})
err := json.Unmarshal([]byte(msg[1:]), ¶ms)
if err != nil {
return closeChannel(c, m, err)
}
c.header.Sid = params["sid"].(string)
if v, ok := params["pingInterval"]; ok {
c.header.PingInterval = int(v.(float64))
} else {
c.header.PingInterval = 25000
}
if v, ok := params["pingTimeout"]; ok {
c.header.PingTimeout = int(v.(float64))
} else {
c.header.PingTimeout = 20000
}
go func() {
// treat the connection establish as first ping
c.pingChan <- true
}()
// in protocol v4 & binary msg Connection to a namespace
if c.conn.GetUseBinaryMessage() {
c.out <- &protocol.MsgPack{
Type: protocol.CONNECT,
Nsp: protocol.DefaultNsp,
Data: &struct {
}{},
}
// in protocol v4 & text msg Connection to a namespace
} else {
c.out <- protocol.CommonMsg + protocol.OpenMsg
}
}
case protocol.CloseMsg:
reconnectErr := reconnectChannel(c, m)
if reconnectErr != nil {
return closeChannel(c, m)
}
case protocol.PingMsg:
go func() {
c.pingChan <- true
}()
// in protocol v4, the server sends a ping, and the client answers with a pong
c.out <- protocol.PongMsg
case protocol.PongMsg:
case protocol.UpgradeMsg:
case protocol.CommonMsg:
// in protocol v3 & binary msg ps: 4{"type":0,"data":null,"nsp":"/","id":0}
// in protocol v3 & text msg ps: 40 or 41 or 42["message", ...]
// in protocol v4 & text msg ps: 40 or 41 or 42["message", ...]
go m.processIncomingMessage(c, msg[1:])
default:
// in protocol v4 & binary msg ps: {"type":0,"data":{"sid":"HWEr440000:1:R1CHyink:shadiao:101"},"nsp":"/","id":0}
go m.processIncomingMessage(c, msg)
}
}
}
func handleReadError(err error, c *Channel, m *methods) error {
if strings.Contains(err.Error(), "use of closed network connection") {
return nil
}
if e, ok := err.(*gorillaws.CloseError); ok && e.Code > 1000 {
reconnectErr := reconnectChannel(c, m)
if reconnectErr != nil {
return err
} else {
return nil
}
} else {
return err
}
}
func outLoop(c *Channel, m *methods) error {
var buffer []interface{}
for {
if c.state.Load() >= ChannelStateClosed {
return nil
}
msg := <-c.out
if msg == protocol.CloseMsg {
return closeChannel(c, m)
}
if msg == protocol.CommonMsg+protocol.OpenMsg {
err := c.conn.WriteMessage(msg)
if err != nil {
return closeChannel(c, m, err)
}
continue
}
var msgpack *protocol.MsgPack
if v, ok := msg.(*protocol.MsgPack); ok {
msgpack = v
}
if msgpack != nil && msgpack.Type == protocol.CONNECT {
err := c.conn.WriteMessage(msg)
if err != nil {
return closeChannel(c, m, err)
}
continue
}
buffer = append(buffer, msg)
if len(buffer) >= queueBufferSize-1 {
closeErr := &websocket.CloseError{}
closeErr.Code = websocket.QueueBufferSizeCode
closeErr.Text = ErrorSocketOverflood.Error()
return closeChannel(c, m, closeErr)
}
if c.state.Load() != ChannelStateConnected {
time.Sleep(100 * time.Millisecond)
continue
}
processed := 0
for _, bm := range buffer {
err := c.conn.WriteMessage(bm)
if err == nil {
processed++
} else {
break
}
if bm == protocol.CloseMsg {
return nil
}
}
buffer = buffer[processed:]
}
}
func pingLoop(c *Channel, m *methods) {
for {
state := c.state.Load()
if state >= ChannelStateClosing {
return
}
if state != ChannelStateConnected {
time.Sleep(200 * time.Millisecond)
continue
}
select {
case <-c.pingChan:
continue
case <-time.After(time.Duration(c.header.PingInterval+c.header.PingTimeout) * time.Millisecond):
if c.state.Load() != ChannelStateConnected {
continue
}
utils.Debug("[ping timeout]")
reconnectErr := reconnectChannel(c, m)
if reconnectErr != nil {
closeChannel(c, m, errors.New("ping timeout"))
return
}
}
}
}
func SchedulePing(c *Channel) {
interval, _ := c.conn.PingParams()
ticker := time.NewTicker(interval)
for {
<-ticker.C
if !c.IsConnected() {
return
}
c.out <- protocol.PingMsg
}
}