-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathWebsocketServer.ts
More file actions
98 lines (78 loc) · 2.5 KB
/
WebsocketServer.ts
File metadata and controls
98 lines (78 loc) · 2.5 KB
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
/**
* The following code is modified based on
* https://github.com/webpack/webpack-dev-server
*
* MIT Licensed
* Author Tobias Koppers @sokra
* Copyright (c) JS Foundation and other contributors
* https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
*/
import WebSocket from 'ws';
import type { Server } from '../server';
import type { ClientConnection, WebSocketServerConfiguration } from '../types';
import BaseServer from './BaseServer';
class WebsocketServer extends BaseServer {
static heartbeatInterval = 1000;
implementation: WebSocket.Server;
constructor(server: Server) {
super(server);
const options: WebSocket.ServerOptions = {
...(this.server.options.webSocketServer as WebSocketServerConfiguration)
.options,
clientTracking: false,
};
const isNoServerMode =
typeof options.port === 'undefined' &&
typeof options.server === 'undefined';
if (isNoServerMode) {
options.noServer = true;
}
this.implementation = new WebSocket.Server(options);
(this.server.server as import('http').Server).on(
'upgrade',
(
req: import('http').IncomingMessage,
sock: import('stream').Duplex,
head: Buffer,
) => {
if (!this.implementation.shouldHandle(req)) {
return;
}
this.implementation.handleUpgrade(req, sock, head, (connection) => {
this.implementation.emit('connection', connection, req);
});
},
);
this.implementation.on('error', (err: Error) => {
this.server.logger.error(err.message);
});
const interval = setInterval(() => {
for (const client of this.clients) {
if (client.isAlive === false) {
client.terminate();
continue;
}
client.isAlive = false;
client.ping(() => {});
}
}, WebsocketServer.heartbeatInterval);
this.implementation.on('connection', (client: ClientConnection) => {
this.clients.push(client);
client.isAlive = true;
client.on('pong', () => {
client.isAlive = true;
});
client.on('close', () => {
this.clients.splice(this.clients.indexOf(client), 1);
});
// TODO: add a test case for this - https://github.com/webpack/webpack-dev-server/issues/5018
client.on('error', (err: Error) => {
this.server.logger.error(err.message);
});
});
this.implementation.on('close', () => {
clearInterval(interval);
});
}
}
module.exports = WebsocketServer;