-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
389 lines (353 loc) · 7.91 KB
/
main.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
package evtWebsocketClient
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"time"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
// Conn is the connection structure.
type Conn struct {
OnMessage func(Msg, *Conn)
OnError func(error)
OnConnected func(*Conn)
MatchMsg func(Msg, Msg) bool
Reconnect bool
MsgPrep func(*Msg)
ws net.Conn
url string
closed bool
msgQueue []Msg
addToQueue chan msgOperation
PingMsg []byte
ComposePingMessage func() []byte
PingIntervalSecs int
CountPongs bool
UnreceivedPingThreshold int
pingCount int
pingTimer time.Time
writerAvailable chan struct{}
readerAvailable chan struct{}
}
// Msg is the message structure.
type Msg struct {
Body []byte
Callback func(Msg, *Conn)
Params map[string]interface{}
}
type msgOperation struct {
add bool
msg *Msg
pos int
}
func (c *Conn) onMsg(pkt []byte) {
msg := Msg{
Body: pkt,
}
if c.MsgPrep != nil {
c.MsgPrep(&msg)
}
var calledBack = false
if c.MatchMsg != nil {
queue := make([]Msg, len(c.msgQueue))
copy(queue, c.msgQueue)
for _, m := range queue {
if m.Callback != nil && c.MatchMsg(msg, m) {
go m.Callback(msg, c)
defer func() {
if r := recover(); r != nil {
fmt.Printf("%v Recovered from error processing message: %v\r\n", time.Now(), r)
}
}()
c.addToQueue <- msgOperation{
add: false,
pos: -1, // i,
msg: &m,
}
calledBack = true
break
}
}
}
// Fire OnMessage every message that hasnt already been handled in a callback
if c.OnMessage != nil && !calledBack {
go c.OnMessage(msg, c)
}
}
func (c *Conn) onError(err error) {
if c.OnError != nil {
c.OnError(err)
}
c.close()
}
func (c *Conn) setupPing() {
if c.PingIntervalSecs > 0 && (c.ComposePingMessage != nil || len(c.PingMsg) > 0) {
if c.CountPongs && c.OnMessage == nil {
c.CountPongs = false
}
c.pingTimer = time.Now().Add(time.Second * time.Duration(c.PingIntervalSecs))
go func() {
for {
if !time.Now().After(c.pingTimer) {
time.Sleep(time.Millisecond * 100)
continue
}
if c.closed {
return
}
var msg []byte
if c.ComposePingMessage != nil {
msg = c.ComposePingMessage()
} else {
msg = c.PingMsg
}
if len(msg) > 0 {
c.write(ws.OpText, msg)
}
c.write(ws.OpPing, []byte(``))
if c.CountPongs {
c.pingCount++
}
if c.pingCount > c.UnreceivedPingThreshold+1 {
c.onError(errors.New("too many pings not responded too"))
return
}
c.pingTimer = time.Now().Add(time.Second * time.Duration(c.PingIntervalSecs))
}
}()
}
}
// PongReceived notify the socket that a ping response (pong) was received, this is left to the user as the message structure can differ between servers
func (c *Conn) PongReceived() {
c.pingCount--
}
// IsConnected tells wether the connection is
// opened or closed.
func (c *Conn) IsConnected() bool {
return !c.closed
}
// Send sends a message through the connection.
func (c *Conn) Send(msg Msg) (err error) {
if msg.Body == nil {
return errors.New("No message body")
}
if c.closed {
return errors.New("closed connection")
}
if msg.Callback != nil && c.addToQueue != nil {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v Recovered from error while sending: %v\r\n", time.Now(), r)
}
}()
c.addToQueue <- msgOperation{
add: true,
pos: -1,
msg: &msg,
}
}
c.write(ws.OpText, msg.Body)
return nil
}
// RemoveFromQueue unregisters a callback from the queue in the event it has timed out
func (c *Conn) RemoveFromQueue(msg Msg) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v Reccovered from error while removing from queue: %v\r\n", time.Now(), r)
}
}()
if c.closed {
return errors.New("closed connection")
}
c.addToQueue <- msgOperation{
add: false,
pos: -1,
msg: &msg,
}
return nil
}
func (c *Conn) read() bool {
defer func() {
if r := recover(); r != nil {
fmt.Printf("%v Recovered from error while reading connection: %v\r\n", time.Now(), r)
}
}()
_, ok := <-c.readerAvailable
if !ok {
return false
}
// m := []wsutil.Message{}
// m, err := wsutil.ReadServerMessage(c.ws, m)
var buf bytes.Buffer
msg, op, err := wsutil.ReadServerData(struct {
io.Reader
io.Writer
}{c.ws, &buf})
if err != nil {
c.onError(err)
return false
}
c.readerAvailable <- struct{}{}
if buf.Len() > 0 {
_, ok := <-c.writerAvailable
if ok {
c.ws.Write(buf.Bytes())
c.writerAvailable <- struct{}{}
}
}
if op == ws.OpClose {
c.close()
return true
}
go c.onMsg(msg)
// for _, msg := range m {
// switch msg.OpCode {
// case ws.OpPing:
// go c.write(ws.OpPong, nil)
// case ws.OpPong:
// go c.PongReceived()
// case ws.OpClose:
// c.close()
// return true
// default:
// go c.onMsg(msg.Payload)
// }
// }
return true
}
func (c *Conn) write(opcode ws.OpCode, pkt []byte) {
defer func() {
if r := recover(); r != nil {
fmt.Printf("%v Recovered from error while writing to connection %v\r\n", time.Now(), r)
}
}()
_, ok := <-c.writerAvailable
if !ok {
return
}
err := wsutil.WriteClientMessage(c.ws, opcode, pkt)
if err != nil {
c.onError(err)
return
}
c.writerAvailable <- struct{}{}
}
func (c *Conn) sendCloseFrame() {
c.write(ws.OpClose, []byte(``))
}
func (c *Conn) startQueueManager() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("%v Reccovered from error while processing message queue: %v\r\n", time.Now(), r)
}
}()
for {
msg, ok := <-c.addToQueue
if !ok {
return
}
if msg.pos == 0 && msg.msg == nil {
return
}
if msg.add {
c.msgQueue = append(c.msgQueue, *msg.msg)
} else {
if msg.pos >= 0 {
c.msgQueue = append(c.msgQueue[:msg.pos], c.msgQueue[msg.pos+1:]...)
} else if c.MatchMsg != nil {
for i, m := range c.msgQueue {
if c.MatchMsg(m, *msg.msg) {
// Delete this element from the queue
c.msgQueue = append(c.msgQueue[:i], c.msgQueue[i+1:]...)
break
}
}
}
}
}
}
// Disconnect sends a close frame and disconnects from the server
func (c *Conn) Disconnect() {
c.close()
}
func (c *Conn) close() {
if c.closed {
return
}
c.closed = true
c.sendCloseFrame()
close(c.readerAvailable)
for _, ok := <-c.readerAvailable; ok; _, ok = <-c.readerAvailable {
}
close(c.writerAvailable)
for _, ok := <-c.writerAvailable; ok; _, ok = <-c.writerAvailable {
}
close(c.addToQueue)
for _, ok := <-c.addToQueue; ok; _, ok = <-c.addToQueue {
}
c.addToQueue = nil
c.ws.Close()
if c.Reconnect {
for {
if err := c.Dial(c.url, ws.DefaultDialer.TLSConfig); err == nil {
break
}
time.Sleep(time.Second * 1)
}
}
}
// Dial sets up the connection with the remote
// host provided in the url parameter.
// Note that all the parameters of the structure
// must have been set before calling it.
// tlsconf is optional and provides settings for handling
// connections to tls setvers via wss protocol
func (c *Conn) Dial(url string, tlsconf *tls.Config) error {
c.closed = true
c.url = url
if c.msgQueue == nil {
c.msgQueue = []Msg{}
}
c.readerAvailable = make(chan struct{}, 1)
c.writerAvailable = make(chan struct{}, 1)
c.pingCount = 0
var err error
if tlsconf != nil {
ws.DefaultDialer.TLSConfig = tlsconf
}
c.ws, _, _, err = ws.Dial(context.Background(), url)
if err != nil {
return err
}
c.closed = false
if c.OnConnected != nil {
go c.OnConnected(c)
}
// setup reader
go func() {
for {
if !c.read() {
return
}
}
}()
// setup write channel
c.addToQueue = make(chan msgOperation) // , 100
// start que manager
go c.startQueueManager()
c.setupPing()
c.readerAvailable <- struct{}{}
c.writerAvailable <- struct{}{}
// resend dropped messages if this is a reconnect
if len(c.msgQueue) > 0 {
for _, msg := range c.msgQueue {
go c.write(ws.OpText, msg.Body)
}
}
return nil
}