WebsocketServer.js
2.43 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
99
100
101
102
103
104
105
"use strict";
const WebSocket = require("ws");
const BaseServer = require("./BaseServer");
/** @typedef {import("../Server").WebSocketServerConfiguration} WebSocketServerConfiguration */
/** @typedef {import("../Server").ClientConnection} ClientConnection */
module.exports = class WebsocketServer extends BaseServer {
static heartbeatInterval = 1000;
/**
* @param {import("../Server")} server
*/
constructor(server) {
super(server);
/** @type {import("ws").ServerOptions} */
const options = {
.../** @type {WebSocketServerConfiguration} */
(this.server.options.webSocketServer).options,
clientTracking: false,
};
const isNoServerMode =
typeof options.port === "undefined" &&
typeof options.server === "undefined";
if (isNoServerMode) {
options.noServer = true;
}
this.implementation = new WebSocket.Server(options);
/** @type {import("http").Server} */
(this.server.server).on(
"upgrade",
/**
* @param {import("http").IncomingMessage} req
* @param {import("stream").Duplex} sock
* @param {Buffer} head
*/
(req, sock, head) => {
if (!this.implementation.shouldHandle(req)) {
return;
}
this.implementation.handleUpgrade(req, sock, head, (connection) => {
this.implementation.emit("connection", connection, req);
});
}
);
this.implementation.on(
"error",
/**
* @param {Error} err
*/
(err) => {
this.server.logger.error(err.message);
}
);
const interval = setInterval(() => {
this.clients.forEach(
/**
* @param {ClientConnection} client
*/
(client) => {
if (client.isAlive === false) {
client.terminate();
return;
}
client.isAlive = false;
client.ping(() => {});
}
);
}, WebsocketServer.heartbeatInterval);
this.implementation.on(
"connection",
/**
* @param {ClientConnection} client
*/
(client) => {
this.clients.push(client);
client.isAlive = true;
client.on("pong", () => {
client.isAlive = true;
});
client.on("close", () => {
this.clients.splice(this.clients.indexOf(client), 1);
});
}
);
this.implementation.on("close", () => {
clearInterval(interval);
});
}
};