0
# Server-Side WebSocket Operations
1
2
Server-side WebSocket implementation providing HTTP server integration, request handling, routing capabilities, and connection management for building WebSocket servers.
3
4
## Capabilities
5
6
### WebSocketServer
7
8
Main server class for handling WebSocket connections attached to HTTP servers.
9
10
```javascript { .api }
11
/**
12
* WebSocket server that handles HTTP upgrade requests
13
* @param config - Server configuration options
14
*/
15
class WebSocketServer extends EventEmitter {
16
constructor(config?: ServerConfig);
17
18
/** Mount server on HTTP server(s) with configuration */
19
mount(config: ServerConfig): void;
20
21
/** Unmount from HTTP server(s) */
22
unmount(): void;
23
24
/** Close all active connections */
25
closeAllConnections(): void;
26
27
/** Broadcast data to all connected clients */
28
broadcast(data: Buffer | string): void;
29
30
/** Broadcast UTF-8 text to all connected clients */
31
broadcastUTF(utfData: string): void;
32
33
/** Broadcast binary data to all connected clients */
34
broadcastBytes(binaryData: Buffer): void;
35
36
/** Gracefully shut down server */
37
shutDown(): void;
38
39
/** Array of active WebSocketConnection instances */
40
readonly connections: WebSocketConnection[];
41
42
/** Array of pending WebSocketRequest instances */
43
readonly pendingRequests: WebSocketRequest[];
44
45
/** Server configuration object */
46
readonly config: ServerConfig;
47
}
48
```
49
50
**Configuration:**
51
52
```javascript { .api }
53
interface ServerConfig {
54
/** HTTP server instance(s) to attach to (required) */
55
httpServer: http.Server | https.Server | http.Server[];
56
57
/** Maximum frame size in bytes (default: 64KiB) */
58
maxReceivedFrameSize?: number;
59
60
/** Maximum message size in bytes (default: 1MiB) */
61
maxReceivedMessageSize?: number;
62
63
/** Whether to fragment outgoing messages (default: true) */
64
fragmentOutgoingMessages?: boolean;
65
66
/** Fragment messages larger than this size (default: 16KiB) */
67
fragmentationThreshold?: number;
68
69
/** Enable keepalive pings (default: true) */
70
keepalive?: boolean;
71
72
/** Keepalive ping interval in milliseconds (default: 20000) */
73
keepaliveInterval?: number;
74
75
/** Drop connection on keepalive timeout (default: true) */
76
dropConnectionOnKeepaliveTimeout?: boolean;
77
78
/** Grace period before dropping connection in milliseconds (default: 10000) */
79
keepaliveGracePeriod?: number;
80
81
/** Use TCP keepalive instead of WebSocket pings (default: false) */
82
useNativeKeepalive?: boolean;
83
84
/** Assemble fragmented messages (default: true) */
85
assembleFragments?: boolean;
86
87
/** Automatically accept all connections (default: false) */
88
autoAcceptConnections?: boolean;
89
90
/** Trust X-Forwarded-For header (default: false) */
91
ignoreXForwardedFor?: boolean;
92
93
/** Parse Cookie headers (default: true) */
94
parseCookies?: boolean;
95
96
/** Parse Sec-WebSocket-Extensions header (default: true) */
97
parseExtensions?: boolean;
98
99
/** Disable Nagle algorithm (default: true) */
100
disableNagleAlgorithm?: boolean;
101
102
/** Close frame timeout in milliseconds (default: 5000) */
103
closeTimeout?: number;
104
}
105
```
106
107
**Events:**
108
109
- `'request'` - `(WebSocketRequest)` - Incoming connection request
110
- `'connect'` - `(WebSocketConnection)` - New connection established
111
- `'close'` - `(WebSocketConnection, closeReason, description)` - Connection closed
112
- `'upgradeError'` - `(error)` - HTTP upgrade error
113
114
**Usage Example:**
115
116
```javascript
117
const WebSocket = require('websocket');
118
const http = require('http');
119
120
// Create HTTP server
121
const httpServer = http.createServer();
122
httpServer.listen(8080);
123
124
// Create WebSocket server
125
const wsServer = new WebSocket.server({
126
httpServer: httpServer,
127
autoAcceptConnections: false,
128
maxReceivedFrameSize: 64 * 1024,
129
maxReceivedMessageSize: 1024 * 1024,
130
keepalive: true,
131
keepaliveInterval: 20000
132
});
133
134
// Handle connection requests
135
wsServer.on('request', function(request) {
136
// Validate origin
137
if (!originIsAllowed(request.origin)) {
138
request.reject(403, 'Origin not allowed');
139
return;
140
}
141
142
const connection = request.accept('echo-protocol', request.origin);
143
console.log('Connection accepted from ' + connection.remoteAddress);
144
});
145
146
// Handle new connections
147
wsServer.on('connect', function(connection) {
148
console.log('New connection established');
149
});
150
151
// Broadcast to all clients
152
wsServer.broadcastUTF('Server message to all clients');
153
```
154
155
### WebSocketRequest
156
157
Represents an incoming WebSocket handshake request on the server side.
158
159
```javascript { .api }
160
/**
161
* Incoming WebSocket handshake request
162
* @param socket - TCP socket
163
* @param httpRequest - HTTP request object
164
* @param serverConfig - Server configuration
165
*/
166
class WebSocketRequest extends EventEmitter {
167
/** Parse WebSocket handshake headers */
168
readHandshake(): void;
169
170
/**
171
* Accept the connection request
172
* @param acceptedProtocol - Protocol to accept (must be in requestedProtocols)
173
* @param allowedOrigin - Origin to include in response
174
* @param cookies - Array of cookie objects to set
175
* @returns WebSocketConnection instance
176
*/
177
accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: Cookie[]): WebSocketConnection;
178
179
/**
180
* Reject the connection request
181
* @param status - HTTP status code (default: 403)
182
* @param reason - Rejection reason string
183
* @param extraHeaders - Additional HTTP headers
184
*/
185
reject(status?: number, reason?: string, extraHeaders?: object): void;
186
187
/** Original HTTP request object */
188
readonly httpRequest: http.IncomingMessage;
189
190
/** TCP socket */
191
readonly socket: net.Socket;
192
193
/** Requested resource path */
194
readonly resource: string;
195
196
/** Parsed URL object */
197
readonly resourceURL: URL;
198
199
/** Sec-WebSocket-Key header value */
200
readonly key: string;
201
202
/** Requested WebSocket version */
203
readonly webSocketVersion: number;
204
205
/** Origin header value */
206
readonly origin: string;
207
208
/** Array of requested protocol strings (lowercase) */
209
readonly requestedProtocols: string[];
210
211
/** Map of lowercase to original case protocols */
212
readonly protocolFullCaseMap: object;
213
214
/** Array of requested extension objects */
215
readonly requestedExtensions: object[];
216
217
/** Array of parsed cookie objects */
218
readonly cookies: Cookie[];
219
220
/** Host header value */
221
readonly host: string;
222
223
/** Client IP address */
224
readonly remoteAddress: string;
225
226
/** Array including X-Forwarded-For addresses */
227
readonly remoteAddresses: string[];
228
}
229
```
230
231
**Events:**
232
233
- `'requestAccepted'` - `(WebSocketConnection)` - Request accepted
234
- `'requestRejected'` - `(WebSocketRequest)` - Request rejected
235
- `'requestResolved'` - `(WebSocketRequest)` - Request resolved (accepted or rejected)
236
237
**Usage Example:**
238
239
```javascript
240
wsServer.on('request', function(request) {
241
console.log('Connection from origin ' + request.origin);
242
console.log('Requested protocols: ' + request.requestedProtocols.join(', '));
243
console.log('Resource: ' + request.resource);
244
245
// Validate the request
246
if (!originIsAllowed(request.origin)) {
247
request.reject(403, 'Origin not allowed');
248
return;
249
}
250
251
if (request.requestedProtocols.indexOf('echo-protocol') === -1) {
252
request.reject(400, 'Unsupported protocol');
253
return;
254
}
255
256
// Accept with specific protocol and cookies
257
const connection = request.accept('echo-protocol', request.origin, [
258
{ name: 'session', value: 'abc123', httponly: true }
259
]);
260
});
261
```
262
263
### WebSocketRouter
264
265
Routes WebSocket requests based on path patterns and protocols.
266
267
```javascript { .api }
268
/**
269
* Routes WebSocket requests based on path and protocol
270
* @param config - Router configuration
271
*/
272
class WebSocketRouter extends EventEmitter {
273
constructor(config?: RouterConfig);
274
275
/** Attach router to WebSocketServer */
276
attachServer(server: WebSocketServer): void;
277
278
/** Detach from WebSocketServer */
279
detachServer(): void;
280
281
/**
282
* Mount route handler
283
* @param path - Path string or RegExp (use '*' for catch-all)
284
* @param protocol - Protocol string (use '*' for any protocol)
285
* @param callback - Function called with WebSocketRouterRequest
286
*/
287
mount(path: string | RegExp, protocol: string, callback: (request: WebSocketRouterRequest) => void): void;
288
289
/**
290
* Remove route handler
291
* @param path - Path string or RegExp
292
* @param protocol - Protocol string
293
*/
294
unmount(path: string | RegExp, protocol: string): void;
295
296
/** Array of mounted route handlers */
297
readonly handlers: RouteHandler[];
298
299
/** Attached WebSocketServer instance */
300
readonly server: WebSocketServer;
301
}
302
303
interface RouterConfig {
304
/** WebSocketServer instance to attach to */
305
server?: WebSocketServer;
306
}
307
```
308
309
**Usage Example:**
310
311
```javascript
312
const router = new WebSocket.router({
313
server: wsServer
314
});
315
316
// Route specific paths and protocols
317
router.mount('/chat', 'chat-protocol', function(request) {
318
console.log('Chat request from ' + request.origin);
319
const connection = request.accept();
320
// Handle chat connection
321
});
322
323
router.mount('/api/*', '*', function(request) {
324
console.log('API request to ' + request.resource);
325
const connection = request.accept();
326
// Handle API connection
327
});
328
329
// Catch-all route
330
router.mount('*', '*', function(request) {
331
console.log('Unhandled request to ' + request.resource);
332
request.reject(404, 'Not found');
333
});
334
```
335
336
### WebSocketRouterRequest
337
338
Wrapper for WebSocketRequest within router context.
339
340
```javascript { .api }
341
/**
342
* WebSocket request within router context
343
* @param webSocketRequest - Original WebSocketRequest
344
* @param resolvedProtocol - Resolved protocol for this route
345
*/
346
class WebSocketRouterRequest extends EventEmitter {
347
/**
348
* Accept the connection
349
* @param origin - Origin to include in response
350
* @param cookies - Array of cookie objects to set
351
*/
352
accept(origin?: string, cookies?: Cookie[]): WebSocketConnection;
353
354
/**
355
* Reject the connection
356
* @param status - HTTP status code
357
* @param reason - Rejection reason
358
* @param extraHeaders - Additional headers
359
*/
360
reject(status?: number, reason?: string, extraHeaders?: object): void;
361
362
/** Original WebSocketRequest */
363
readonly webSocketRequest: WebSocketRequest;
364
365
/** Resolved protocol for this route */
366
readonly protocol: string;
367
368
// Inherited from WebSocketRequest
369
readonly origin: string;
370
readonly resource: string;
371
readonly resourceURL: URL;
372
readonly httpRequest: http.IncomingMessage;
373
readonly remoteAddress: string;
374
readonly webSocketVersion: number;
375
readonly requestedExtensions: object[];
376
readonly cookies: Cookie[];
377
}
378
```
379
380
**Events:**
381
382
- `'requestAccepted'` - `(WebSocketConnection)` - Request accepted
383
- `'requestRejected'` - `(WebSocketRouterRequest)` - Request rejected
384
385
## Types
386
387
### Cookie Object
388
389
```javascript { .api }
390
interface Cookie {
391
name: string;
392
value: string;
393
path?: string;
394
domain?: string;
395
expires?: Date;
396
maxage?: number;
397
secure?: boolean;
398
httponly?: boolean;
399
}
400
```
401
402
### Route Handler
403
404
```javascript { .api }
405
interface RouteHandler {
406
path: string | RegExp;
407
protocol: string;
408
callback: (request: WebSocketRouterRequest) => void;
409
}
410
```