forked from muka/peerjs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wss.go
235 lines (204 loc) · 5.23 KB
/
wss.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
package server
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/muka/peerjs-go/emitter"
"github.com/muka/peerjs-go/models"
"github.com/sirupsen/logrus"
)
// ClientMessage wrap a message received by a client
type ClientMessage struct {
Client IClient
Message *models.Message
}
//NewWebSocketServer create a new WebSocketServer
func NewWebSocketServer(realm IRealm, opts Options) *WebSocketServer {
wss := WebSocketServer{
Emitter: emitter.NewEmitter(),
upgrader: websocket.Upgrader{},
log: createLogger("websocket-server", opts),
realm: realm,
opts: opts,
}
wss.upgrader.CheckOrigin = func(r *http.Request) bool {
// TODO: expose as options
return true
}
return &wss
}
// WebSocketServer wrap the websocket server
type WebSocketServer struct {
emitter.Emitter
upgrader websocket.Upgrader
clients []*websocket.Conn
cMutex sync.Mutex
log *logrus.Entry
realm IRealm
opts Options
}
// Send send data to the clients
func (wss *WebSocketServer) Send(data []byte) {
for _, conn := range wss.clients {
err := conn.WriteMessage(websocket.BinaryMessage, data)
if err != nil {
wss.log.Warnf("Write failed: %s", err)
}
}
}
//onSocketConnection called when a client connect
func (wss *WebSocketServer) sendErrorAndClose(conn *websocket.Conn, msg string) error {
err := conn.WriteJSON(models.Message{
Type: MessageTypeError,
Payload: models.Payload{
Msg: msg,
},
})
if err != nil {
return err
}
err = conn.Close()
if err != nil {
return err
}
return nil
}
//
func (wss *WebSocketServer) configureWS(conn *websocket.Conn, client IClient) error {
client.SetSocket(conn)
conn.SetPingHandler(func(appData string) error {
// wss.log.Debugf("[%s] Ping received", client.GetID())
client.SetLastPing(getTime())
return nil
})
closed := false
conn.SetCloseHandler(func(code int, text string) error {
// if any close error happens, stop the loop and remove the client
wss.log.Debugf("Closed connection, cleaning up %s", client.GetID())
if client.GetSocket() == conn {
wss.realm.RemoveClientByID(client.GetID())
}
conn.Close()
wss.Emit(WebsocketEventClose, client)
closed = true
return nil
})
go func() {
for {
if closed {
return
}
_, raw, err := conn.ReadMessage()
if err != nil {
wss.log.Errorf("[%s] Read WS error: %s", client.GetID(), err)
return
}
// message handling
data, err := ioutil.ReadAll(bytes.NewReader(raw))
if err != nil {
wss.log.Errorf("client message read error: %s", err)
wss.Emit(WebsocketEventError, err)
continue
}
message := new(models.Message)
err = json.Unmarshal(data, message)
if err != nil {
wss.log.Errorf("client message unmarshal error: %s", err)
wss.Emit(WebsocketEventError, err)
continue
}
message.Src = client.GetID()
wss.Emit(WebsocketEventMessage, ClientMessage{client, message})
}
}()
wss.Emit(WebsocketEventConnection, client)
return nil
}
//registerClient
func (wss *WebSocketServer) registerClient(conn *websocket.Conn, id, token string) error {
// Check concurrent limit
clientsCount := len(wss.realm.GetClientsIds())
if clientsCount >= wss.opts.ConcurrentLimit {
err := wss.sendErrorAndClose(conn, ErrorConnectionLimitExceeded)
if err != nil {
wss.log.Errorf("[sendErrorAndClose] Error: %s", err)
}
return nil
}
client := NewClient(id, token)
wss.realm.SetClient(client, id)
err := conn.WriteJSON(models.Message{Type: MessageTypeOpen})
if err != nil {
return err
}
err = wss.configureWS(conn, client)
if err != nil {
return err
}
return nil
}
//onSocketConnection called when a client connect
func (wss *WebSocketServer) onSocketConnection(conn *websocket.Conn, r *http.Request) {
query := r.URL.Query()
id := query.Get("id")
token := query.Get("token")
key := query.Get("key")
if id == "" || token == "" || key == "" {
err := wss.sendErrorAndClose(conn, ErrorInvalidWSParameters)
if err != nil {
wss.log.Errorf("[sendErrorAndClose] Error: %s", err)
}
return
}
if key != wss.opts.Key {
err := wss.sendErrorAndClose(conn, ErrorInvalidKey)
if err != nil {
wss.log.Errorf("[sendErrorAndClose] Error: %s", err)
}
return
}
client := wss.realm.GetClientByID(id)
if client == nil {
err := wss.registerClient(conn, id, token)
if err != nil {
wss.log.Errorf("[registerClient] Error: %s", err)
}
return
}
if token != client.GetToken() {
// ID-taken, invalid token
err := conn.WriteJSON(models.Message{
Type: MessageTypeIDTaken,
Payload: models.Payload{
Msg: "ID is taken",
},
})
if err != nil {
wss.log.Errorf("[%s] Failed to write message: %s", MessageTypeIDTaken, err)
}
go func() {
// wait for the client to receive the response message
<-time.After(time.Millisecond * 100)
conn.Close()
}()
return
}
wss.configureWS(conn, client)
}
// Handler expose the http handler for websocket
func (wss *WebSocketServer) Handler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := wss.upgrader.Upgrade(w, r, nil)
if err != nil {
wss.log.Warnf("upgrade error: %s", err)
w.WriteHeader(500)
// next.ServeHTTP(w, r)
return
}
wss.onSocketConnection(c, r)
})
}