-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathws.go
93 lines (75 loc) · 1.32 KB
/
ws.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
package traqwsbot
import (
"sync"
"github.com/gorilla/websocket"
)
// rawMessage indicates a raw WebSocket message.
type rawMessage struct {
t int
data []byte
}
// wsConn is a light-weight wrapper of *websocket.Conn.
type wsConn struct {
conn *websocket.Conn
send chan *rawMessage
closed bool
sync.RWMutex
textMessageHandler func(p []byte)
}
func newWSConn(conn *websocket.Conn) *wsConn {
return &wsConn{
conn: conn,
send: make(chan *rawMessage),
closed: false,
}
}
func (w *wsConn) OnTextMessage(h func(p []byte)) {
w.textMessageHandler = h
}
func (w *wsConn) Start() {
go w.writeLoop()
w.readLoop()
}
func (w *wsConn) WriteMessage(m *rawMessage) {
w.send <- m
}
func (w *wsConn) readLoop() {
defer w.close()
for {
t, p, err := w.conn.ReadMessage()
if err != nil {
return
}
switch t {
case websocket.TextMessage:
w.textMessageHandler(p)
case websocket.BinaryMessage:
// Not supported, just ignore it
}
}
}
func (w *wsConn) writeLoop() {
defer w.close()
for {
m, ok := <-w.send
if !ok {
return
}
if err := w.conn.WriteMessage(m.t, m.data); err != nil {
return
}
if m.t == websocket.CloseMessage {
return
}
}
}
func (w *wsConn) close() {
w.Lock()
defer w.Unlock()
if w.closed {
return
}
w.closed = true
_ = w.conn.Close()
close(w.send)
}