-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.go
293 lines (242 loc) · 8.05 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
package sio
import (
"net/http"
"time"
"github.com/karagenc/socket.io-go/adapter"
eio "github.com/karagenc/socket.io-go/engine.io"
"github.com/karagenc/socket.io-go/parser"
jsonparser "github.com/karagenc/socket.io-go/parser/json"
"github.com/karagenc/socket.io-go/parser/json/serializer/stdjson"
)
const (
DefaultConnectTimeout = time.Second * 45
DefaultMaxDisconnectionDuration = time.Minute * 2
)
type BroadcastOperator = adapter.BroadcastOperator
type (
ServerConfig struct {
// For custom parsers
ParserCreator parser.Creator
// For custom adapters
AdapterCreator adapter.Creator
// Engine.IO configuration
EIO eio.ServerConfig
// Duration to wait before a client without namespace is closed.
//
// Default: 45 seconds
ConnectTimeout time.Duration
// In order for a client to make a connection to a namespace,
// the namespace must be created on server via `Server.of`.
//
// This option permits the client to create the namespace if it is not already created on server.
// If this option is disabled, only namespaces created on the server can be connected.
//
// Default: false
AcceptAnyNamespace bool
ServerConnectionStateRecovery ServerConnectionStateRecovery
// For debugging purposes. Leave it nil if it is of no use.
//
// This only applies to Socket.IO. For Engine.IO, use EIO.Debugger.
Debugger Debugger
}
ServerConnectionStateRecovery struct {
// Enable connection state recovery
//
// Default: false
Enabled bool
// The backup duration of the sessions and the packets
//
// Default: 2 minutes
MaxDisconnectionDuration time.Duration
// Whether to execute middlewares upon successful connection state recovery.
//
// Default: false
UseMiddlewares bool
}
Server struct {
parserCreator parser.Creator
adapterCreator adapter.Creator
eio *eio.Server
namespaces *nspStore
connectTimeout time.Duration
acceptAnyNamespace bool
connectionStateRecovery ServerConnectionStateRecovery
debug Debugger
newNamespaceHandlers *handlerStore[*ServerNewNamespaceFunc]
anyConnectionHandlers *handlerStore[*ServerAnyConnectionFunc]
}
)
func NewServer(config *ServerConfig) *Server {
if config == nil {
config = new(ServerConfig)
}
server := &Server{
parserCreator: config.ParserCreator,
adapterCreator: config.AdapterCreator,
namespaces: newNspStore(),
acceptAnyNamespace: config.AcceptAnyNamespace,
connectionStateRecovery: config.ServerConnectionStateRecovery,
newNamespaceHandlers: newHandlerStore[*ServerNewNamespaceFunc](),
anyConnectionHandlers: newHandlerStore[*ServerAnyConnectionFunc](),
}
if config.Debugger != nil {
server.debug = config.Debugger
} else {
server.debug = newNoopDebugger()
}
server.debug = server.debug.WithContext("[sio/server] Server")
server.eio = eio.NewServer(server.onEIOSocket, &config.EIO)
if server.parserCreator == nil {
json := stdjson.New()
server.parserCreator = jsonparser.NewCreator(0, json)
}
if server.connectionStateRecovery.Enabled {
if server.connectionStateRecovery.MaxDisconnectionDuration == 0 {
server.connectionStateRecovery.MaxDisconnectionDuration = DefaultMaxDisconnectionDuration
}
if server.adapterCreator == nil {
server.adapterCreator = adapter.NewSessionAwareAdapterCreator(server.connectionStateRecovery.MaxDisconnectionDuration)
}
} else {
if server.adapterCreator == nil {
server.adapterCreator = adapter.NewInMemoryAdapterCreator()
}
}
if config.ConnectTimeout != 0 {
server.connectTimeout = config.ConnectTimeout
} else {
server.connectTimeout = DefaultConnectTimeout
}
return server
}
func (s *Server) onEIOSocket(eioSocket eio.ServerSocket) *eio.Callbacks {
_, callbacks := newServerConn(s, eioSocket, s.parserCreator)
return callbacks
}
func (s *Server) Of(namespace string) *Namespace {
if len(namespace) == 0 || (len(namespace) != 0 && namespace[0] != '/') {
namespace = "/" + namespace
}
n, created := s.namespaces.getOrCreate(namespace, s, s.adapterCreator, s.parserCreator)
if created && namespace != "/" {
s.newNamespaceHandlers.forEach(func(handler *ServerNewNamespaceFunc) { (*handler)(n) }, true)
}
return n
}
// Alias of: s.Of("/").Use(...)
func (s *Server) Use(f NspMiddlewareFunc) {
s.Of("/").Use(f)
}
// Alias of: s.Of("/").OnConnection(...)
func (s *Server) OnConnection(f NamespaceConnectionFunc) {
s.Of("/").OnConnection(f)
}
// Alias of: s.Of("/").OnceConnection(...)
func (s *Server) OnceConnection(f NamespaceConnectionFunc) {
s.Of("/").OnceConnection(f)
}
// Alias of: s.Of("/").OffConnection(...)
func (s *Server) OffConnection(f ...NamespaceConnectionFunc) {
s.Of("/").OffConnection(f...)
}
// Emits an event to all connected clients in the given namespace.
//
// Alias of: s.Of("/").Emit(...)
func (s *Server) Emit(eventName string, v ...any) {
s.Of("/").Emit(eventName, v...)
}
// Sets a modifier for a subsequent event emission that the event
// will only be broadcast to clients that have joined the given room.
//
// To emit to multiple rooms, you can call `To` several times.
//
// Alias of: s.Of("/").To(...)
func (s *Server) To(room ...Room) *BroadcastOperator {
return s.Of("/").To(room...)
}
// Alias of: s.Of("/").In(...)
func (s *Server) In(room ...Room) *BroadcastOperator {
return s.Of("/").In(room...)
}
// Sets a modifier for a subsequent event emission that the event
// will only be broadcast to clients that have not joined the given rooms.
//
// Alias of: s.Of("/").To(...)
func (s *Server) Except(room ...Room) *BroadcastOperator {
return s.Of("/").Except(room...)
}
// Compression flag is unused at the moment, thus setting this will have no effect on compression.
//
// Alias of: s.Of("/").Compress(...)
func (s *Server) Compress(compress bool) *BroadcastOperator {
return s.Of("/").Compress(compress)
}
// Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node (when scaling to multiple nodes).
//
// See: https://socket.io/docs/v4/using-multiple-nodes
//
// Alias of: s.Of("/").Local(...)
func (s *Server) Local() *BroadcastOperator {
return s.Of("/").Local()
}
// Gets the sockets of the namespace.
// Beware that this is local to the current node. For sockets across all nodes, use FetchSockets
//
// Alias of: s.Of("/").Sockets(...)
func (s *Server) Sockets() []ServerSocket {
return s.Of("/").Sockets()
}
// Returns the matching socket instances. This method works across a cluster of several Socket.IO servers.
//
// Alias of: s.Of("/").FetchSockets(...)
func (s *Server) FetchSockets(room ...string) []adapter.Socket {
return s.Of("/").FetchSockets()
}
// Makes the matching socket instances leave the specified rooms.
//
// Alias of: s.Of("/").SocketsJoin(...)
func (s *Server) SocketsJoin(room ...Room) {
s.Of("/").SocketsJoin(room...)
}
// Makes the matching socket instances leave the specified rooms.
//
// Alias of: s.Of("/").SocketsLeave(...)
func (s *Server) SocketsLeave(room ...Room) {
s.Of("/").SocketsLeave(room...)
}
// Makes the matching socket instances disconnect from the namespace.
//
// If value of close is true, closes the underlying connection. Otherwise, it just disconnects the namespace.
//
// Alias of: s.Of("/").DisconnectSockets(...)
func (s *Server) DisconnectSockets(close bool) {
s.Of("/").DisconnectSockets(close)
}
// Sends a message to the other Socket.IO servers of the cluster.
func (s *Server) ServerSideEmit(eventName string, v ...any) {
s.Of("/").ServerSideEmit(eventName, v...)
}
// Start the server.
func (s *Server) Run() error {
return s.eio.Run()
}
func (s *Server) PollTimeout() time.Duration {
return s.eio.PollTimeout()
}
func (s *Server) HTTPWriteTimeout() time.Duration {
return s.eio.HTTPWriteTimeout()
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.eio.ServeHTTP(w, r)
}
func (s *Server) IsClosed() bool {
return s.eio.IsClosed()
}
// Shut down the server. Server cannot be restarted once it is closed.
func (s *Server) Close() error {
for _, _socket := range s.Sockets() {
socket := _socket.(*serverSocket)
socket.onClose(ReasonServerShuttingDown)
}
return s.eio.Close()
}