-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.go
156 lines (142 loc) · 3.74 KB
/
websocket.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
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the peer.
writeWait = 50 * time.Second // TODO: make this configurable
// Time allowed to read the next pong message from the peer.
pongWait = 50 * time.Second // TODO: make this configurable
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 10000000
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true // TODO: implement origin checking
},
}
type wsServer struct {
}
type wsConn struct {
conn *websocket.Conn
session *session
send chan *websocket.PreparedMessage
closeWritePump chan struct{}
}
func newWsConn(session *session, conn *websocket.Conn) *wsConn {
return &wsConn{
conn: conn,
session: session,
send: make(chan *websocket.PreparedMessage, 5),
closeWritePump: make(chan struct{}, 0),
}
}
func (wsConn *wsConn) WriteMessage(m []byte, pm *websocket.PreparedMessage) {
defer func() {
recover() // recover if channel is already closed
}()
debugMessageType("sending message to client..", m)
wsConn.send <- pm
}
func (wsConn *wsConn) readPump() {
wsConn.conn.SetReadLimit(maxMessageSize)
wsConn.conn.SetReadDeadline(time.Now().Add(pongWait))
wsConn.conn.SetPongHandler(func(string) error {
wsConn.conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
for {
_, message, err := wsConn.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("ydb error: %v", err)
}
break
}
mbuffer := bytes.NewBuffer(message)
for {
err := readMessage(mbuffer, wsConn.session)
if err != nil {
break
}
}
}
close(wsConn.closeWritePump)
wsConn.conn.Close()
debug("ending read pump for ws conn")
// TODO: unregister conn from ydb
}
func (wsConn *wsConn) writePump() {
conn := wsConn.conn
ticker := time.NewTicker(pingPeriod)
defer func() {
debug("ending write pump for ws conn")
ticker.Stop()
wsConn.session.removeConn(wsConn)
close(wsConn.send)
conn.Close()
}()
for {
select {
case <-wsConn.closeWritePump:
return
case message, ok := <-wsConn.send:
conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
err := conn.WritePreparedMessage(message)
if err != nil {
fmt.Println("server error when writing prepared message to conn", err)
return
}
case <-ticker.C:
conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := wsConn.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
func setupWebsocketsListener(addr string) {
// TODO: only set this if in testing mode!
http.HandleFunc("/clearAll", func(w http.ResponseWriter, r *http.Request) {
unsafeClearAllYdbContent()
w.WriteHeader(200)
fmt.Fprintf(w, "OK")
})
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("new client..")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Printf("error: error upgrading client %s", err.Error())
return
}
var sessionid uint64 // TODO: get the sessionid from http headers
var session *session
if sessionid == 0 {
session = ydb.createSession()
} else {
session = ydb.getSession(sessionid)
}
wsConn := newWsConn(session, conn)
session.add(wsConn)
go wsConn.readPump()
go wsConn.writePump()
})
err := http.ListenAndServe(addr, nil)
if err != nil {
exitBecause(err.Error())
}
}