-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_wrapper.go
107 lines (88 loc) · 2.09 KB
/
socket_wrapper.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
package msg2api
import (
"encoding/json"
"errors"
"github.com/gorilla/websocket"
"io"
"time"
)
const pingTimeout = 5 * time.Minute
var errBadFrameType = errors.New("bad frame type")
type socketWrapper struct {
socket *websocket.Conn
sendQ chan []byte
sendErrQ chan error
}
func (w *socketWrapper) runQueues() {
ping := time.NewTicker(pingTimeout / 3)
defer ping.Stop()
for {
select {
case msg, open := <-w.sendQ:
if !open {
return
}
w.sendErrQ <- w.socket.WriteMessage(websocket.TextMessage, msg)
case <-ping.C:
if err := w.socket.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
func (w *socketWrapper) receiveFrame() ([]byte, error) {
msgType, msg, err := w.socket.ReadMessage()
switch {
case msgType == websocket.CloseMessage:
case err == io.EOF:
return nil, io.EOF
case msgType == websocket.TextMessage:
return msg, err
}
w.Close(websocket.CloseUnsupportedData, "")
return nil, errBadFrameType
}
func (w *socketWrapper) Receive() (string, error) {
msg, err := w.receiveFrame()
if err != nil {
return "", err
}
return string(msg), nil
}
func (w *socketWrapper) ReceiveJSON(value interface{}) error {
msg, err := w.receiveFrame()
if err != nil {
return err
}
return json.Unmarshal(msg, value)
}
func (w *socketWrapper) Write(msg string) error {
w.sendQ <- []byte(msg)
return <-w.sendErrQ
}
func (w *socketWrapper) WriteJSON(value interface{}) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
w.sendQ <- data
return <-w.sendErrQ
}
func (w *socketWrapper) Close(reason int, msg string) {
if w.sendQ != nil {
close(w.sendQ)
}
w.sendQ = nil
w.socket.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(reason, msg))
w.socket.Close()
}
func wrapWebsocket(socket *websocket.Conn) *socketWrapper {
result := &socketWrapper{socket, make(chan []byte), make(chan error)}
socket.SetReadDeadline(time.Now().Add(pingTimeout))
socket.SetPongHandler(func(string) error {
socket.SetReadDeadline(time.Now().Add(pingTimeout))
return nil
})
go result.runQueues()
return result
}