forked from graarh/golang-socketio
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.go
295 lines (246 loc) · 7.55 KB
/
server.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package gosocketio
import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net/http"
"sync"
"time"
"github.com/mtfelian/golang-socketio/logging"
"github.com/mtfelian/golang-socketio/protocol"
"github.com/mtfelian/golang-socketio/transport"
)
var (
ErrorServerNotSet = errors.New("server was not set")
ErrorConnectionNotFound = errors.New("connection not found")
)
// Server represents a socket.io server instance
type Server struct {
*event
http.Handler
channels map[string]map[*Channel]struct{} // maps room name to map of channels to an empty struct
rooms map[*Channel]map[string]struct{} // maps channel to map of room names to an empty struct
channelsMu sync.RWMutex
sids map[string]*Channel // maps channel id to channel
sidsMu sync.RWMutex
websocket *transport.WebsocketTransport
polling *transport.PollingTransport
}
// NewServer creates new socket.io server
func NewServer() *Server {
s := &Server{
websocket: transport.DefaultWebsocketTransport(),
polling: transport.DefaultPollingTransport(),
channels: make(map[string]map[*Channel]struct{}),
rooms: make(map[*Channel]map[string]struct{}),
sids: make(map[string]*Channel),
event: &event{
onConnection: onConnection,
onDisconnection: onDisconnection,
},
}
s.event.init()
return s
}
// GetChannel by it's sid
func (s *Server) GetChannel(sid string) (*Channel, error) {
s.sidsMu.RLock()
defer s.sidsMu.RUnlock()
c, ok := s.sids[sid]
if !ok {
return nil, ErrorConnectionNotFound
}
return c, nil
}
// Get amount of channels, joined to given room, using server
func (s *Server) Amount(room string) int {
s.channelsMu.RLock()
defer s.channelsMu.RUnlock()
roomChannels, _ := s.channels[room]
return len(roomChannels)
}
// List returns a list of channels joined to the given room, using server
func (s *Server) List(room string) []*Channel {
s.channelsMu.RLock()
defer s.channelsMu.RUnlock()
roomChannels, ok := s.channels[room]
if !ok {
return []*Channel{}
}
i := 0
roomChannelsCopy := make([]*Channel, len(roomChannels))
for channel := range roomChannels {
roomChannelsCopy[i] = channel
i++
}
return roomChannelsCopy
}
// BroadcastTo the the given room an handler with payload, using server
func (s *Server) BroadcastTo(room, name string, payload interface{}) {
s.channelsMu.RLock()
defer s.channelsMu.RUnlock()
roomChannels, ok := s.channels[room]
if !ok {
return
}
for cn := range roomChannels {
if cn.IsAlive() {
go cn.Emit(name, payload)
}
}
}
// Broadcast to all clients
func (s *Server) BroadcastToAll(method string, payload interface{}) {
s.sidsMu.RLock()
defer s.sidsMu.RUnlock()
for _, cn := range s.sids {
if cn.IsAlive() {
go cn.Emit(method, payload)
}
}
}
// onConnection fires on connection and on connection upgrade
func onConnection(c *Channel) {
c.server.sidsMu.Lock()
c.server.sids[c.Id()] = c
c.server.sidsMu.Unlock()
}
// onDisconnection fires on disconnection
func onDisconnection(c *Channel) {
c.server.channelsMu.Lock()
defer c.server.channelsMu.Unlock()
defer func() {
c.server.sidsMu.Lock()
delete(c.server.sids, c.Id())
c.server.sidsMu.Unlock()
}()
_, ok := c.server.rooms[c]
if !ok {
return
}
for room := range c.server.rooms[c] {
if curRoom, ok := c.server.channels[room]; ok {
delete(curRoom, c)
if len(curRoom) == 0 {
delete(c.server.channels, room)
}
}
}
delete(c.server.rooms, c)
}
// sendOpenSequence to the given channel c
func (s *Server) sendOpenSequence(c *Channel) {
jsonHdr, err := json.Marshal(&c.connHeader)
if err != nil {
panic(err)
}
c.outC <- protocol.MustEncode(&protocol.Message{Type: protocol.MessageTypeOpen, Args: string(jsonHdr)})
c.outC <- protocol.MustEncode(&protocol.Message{Type: protocol.MessageTypeEmpty})
}
// setupEventLoop for the given connection conn on the given address with HTTP header
func (s *Server) setupEventLoop(conn transport.Connection, address string, header http.Header) {
interval, timeout := conn.PingParams()
connHeader := connectionHeader{
Sid: func(s string) string {
hash := fmt.Sprintf("%s %s %b %b", s, time.Now(), rand.Uint32(), rand.Uint32())
buf, sum := bytes.NewBuffer(nil), md5.Sum([]byte(hash))
encoder := base64.NewEncoder(base64.URLEncoding, buf)
encoder.Write(sum[:])
encoder.Close()
return buf.String()[:20]
}(address),
Upgrades: []string{"websocket"},
PingInterval: int(interval / time.Millisecond),
PingTimeout: int(timeout / time.Millisecond),
}
c := &Channel{conn: conn, address: address, header: header, server: s, connHeader: connHeader}
c.init()
switch conn.(type) {
case *transport.PollingConnection:
conn.(*transport.PollingConnection).Transport.SetSid(connHeader.Sid, conn)
}
s.sendOpenSequence(c)
go c.inLoop(s.event)
go c.outLoop(s.event)
s.callHandler(c, OnConnection)
}
// upgradeEventLoop at transport upgrade
func (s *Server) upgradeEventLoop(conn transport.Connection, remoteAddr string, header http.Header, sid string) {
logging.Log().Debug("Server.upgradeEventLoop() fired")
pollingChannel, err := s.GetChannel(sid)
if err != nil {
logging.Log().Warn("Server.upgradeEventLoop() can't find channel for session:", sid)
return
}
logging.Log().Debug("Server.upgradeEventLoop() obtained a polling channel")
interval, timeout := conn.PingParams()
connHeader := connectionHeader{
Sid: sid,
Upgrades: []string{},
PingInterval: int(interval / time.Millisecond),
PingTimeout: int(timeout / time.Millisecond),
}
c := &Channel{conn: conn, address: remoteAddr, header: header, server: s, connHeader: connHeader}
c.init()
logging.Log().Debug("Server.upgradeEventLoop() initialized a new channel")
go c.inLoop(s.event)
go c.outLoop(s.event)
logging.Log().Debug("Server.upgradeEventLoop() fired c.inLoop() and c.outLoop() in separate go-routines")
onConnection(c)
// synchronize stubbing polling channel with receiving "2probe" message
<-c.upgradedC
pollingChannel.stub()
}
// ServeHTTP makes Server to implement http.Handler
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session, transportName := r.URL.Query().Get("sid"), r.URL.Query().Get("transport")
switch transportName {
case "polling":
// session is empty in first polling request, or first and single websocket request
if session != "" {
s.polling.Serve(w, r)
return
}
conn, err := s.polling.HandleConnection(w, r)
if err != nil {
return
}
s.setupEventLoop(conn, r.RemoteAddr, r.Header)
logging.Log().Debug("Server.ServeHTTP() created a PollingConnection")
conn.(*transport.PollingConnection).PollingWriter(w, r)
case "websocket":
if session != "" {
logging.Log().Debug("Server.ServeHTTP() is firing s.websocket.HandleConnection() for upgrade")
conn, err := s.websocket.HandleConnection(w, r)
if err != nil {
logging.Log().Debug("Server.ServeHTTP() upgrade error:", err)
return
}
s.upgradeEventLoop(conn, r.RemoteAddr, r.Header, session)
logging.Log().Debug("Server.ServeHTTP() upgraded to a WebsocketConnection")
return
}
conn, err := s.websocket.HandleConnection(w, r)
if err != nil {
return
}
s.setupEventLoop(conn, r.RemoteAddr, r.Header)
logging.Log().Debug("Server.ServeHTTP() created a WebsocketConnection")
}
}
// CountChannels returns an amount of connected channels
func (s *Server) CountChannels() int {
s.sidsMu.RLock()
defer s.sidsMu.RUnlock()
return len(s.sids)
}
// CountRooms returns an amount of rooms with at least one joined channel
func (s *Server) CountRooms() int {
s.channelsMu.RLock()
defer s.channelsMu.RUnlock()
return len(s.channels)
}