forked from tinode/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hdl_websock.go
168 lines (143 loc) · 4.14 KB
/
hdl_websock.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
/******************************************************************************
*
* Description :
*
* Handler of websocket connections. See also hdl_longpoll.go for long polling
* and hdl_grpc.go for gRPC.
*
*****************************************************************************/
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = idleSessionTimeout
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
func (sess *Session) closeWS() {
if sess.proto == WEBSOCK {
sess.ws.Close()
}
}
func (sess *Session) readLoop() {
defer func() {
sess.closeWS()
count := sess.cleanUp()
log.Println("ws.readLoop exited", sess.sid, count)
}()
sess.ws.SetReadLimit(globals.maxMessageSize)
sess.ws.SetReadDeadline(time.Now().Add(pongWait))
sess.ws.SetPongHandler(func(string) error {
sess.ws.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
sess.remoteAddr = sess.ws.RemoteAddr().String()
for {
// Read a ClientComMessage
_, raw, err := sess.ws.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure,
websocket.CloseNormalClosure) {
log.Println("ws.readLoop", sess.sid, err)
}
return
}
sess.dispatchRaw(raw)
}
}
func (sess *Session) writeLoop() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
// Break readLoop.
sess.closeWS()
log.Println("ws.writeLoop exited", sess.sid)
}()
for {
select {
case msg, ok := <-sess.send:
if !ok {
// Channel closed.
return
}
if err := wsWrite(sess.ws, websocket.TextMessage, msg); err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure,
websocket.CloseNormalClosure) {
log.Println("ws.writeLoop", sess.sid, err)
}
return
}
case msg := <-sess.stop:
// Shutdown requested, don't care if the message is delivered
if msg != nil {
wsWrite(sess.ws, websocket.TextMessage, msg)
}
return
case topic := <-sess.detach:
sess.delSub(topic)
case <-ticker.C:
if err := wsWrite(sess.ws, websocket.PingMessage, nil); err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure,
websocket.CloseNormalClosure) {
log.Println("ws.writeLoop: ping", sess.sid, err)
}
return
}
}
}
}
// Writes a message with the given message type (mt) and payload.
func wsWrite(ws *websocket.Conn, mt int, msg interface{}) error {
var bits []byte
if msg != nil {
bits = msg.([]byte)
} else {
bits = []byte{}
}
ws.SetWriteDeadline(time.Now().Add(writeWait))
return ws.WriteMessage(mt, bits)
}
// Handles websocket requests from peers
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// Allow connections from any Origin
CheckOrigin: func(r *http.Request) bool { return true },
}
func serveWebSocket(wrt http.ResponseWriter, req *http.Request) {
now := time.Now().UTC().Round(time.Millisecond)
if isValid, _ := checkAPIKey(getAPIKey(req)); !isValid {
wrt.WriteHeader(http.StatusForbidden)
json.NewEncoder(wrt).Encode(ErrAPIKeyRequired(now))
log.Println("ws: Missing, invalid or expired API key")
return
}
if req.Method != http.MethodGet {
wrt.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(wrt).Encode(ErrOperationNotAllowed("", "", now))
log.Println("ws: Invalid HTTP method", req.Method)
return
}
ws, err := upgrader.Upgrade(wrt, req, nil)
if _, ok := err.(websocket.HandshakeError); ok {
log.Println("ws: Not a websocket handshake")
return
} else if err != nil {
log.Println("ws: failed to Upgrade ", err)
return
}
sess, count := globals.sessionStore.NewSession(ws, "")
log.Println("ws: session started", sess.sid, count)
// Do work in goroutines to return from serveWebSocket() to release file pointers.
// Otherwise "too many open files" will happen.
go sess.writeLoop()
go sess.readLoop()
}