1 | 'use strict';
|
---|
2 |
|
---|
3 | /* eslint-disable
|
---|
4 | class-methods-use-this
|
---|
5 | */
|
---|
6 | const ws = require('ws');
|
---|
7 | const BaseServer = require('./BaseServer');
|
---|
8 |
|
---|
9 | module.exports = class WebsocketServer extends BaseServer {
|
---|
10 | constructor(server) {
|
---|
11 | super(server);
|
---|
12 | this.wsServer = new ws.Server({
|
---|
13 | noServer: true,
|
---|
14 | path: this.server.sockPath,
|
---|
15 | });
|
---|
16 |
|
---|
17 | this.server.listeningApp.on('upgrade', (req, sock, head) => {
|
---|
18 | if (!this.wsServer.shouldHandle(req)) {
|
---|
19 | return;
|
---|
20 | }
|
---|
21 |
|
---|
22 | this.wsServer.handleUpgrade(req, sock, head, (connection) => {
|
---|
23 | this.wsServer.emit('connection', connection, req);
|
---|
24 | });
|
---|
25 | });
|
---|
26 |
|
---|
27 | this.wsServer.on('error', (err) => {
|
---|
28 | this.server.log.error(err.message);
|
---|
29 | });
|
---|
30 |
|
---|
31 | const noop = () => {};
|
---|
32 |
|
---|
33 | setInterval(() => {
|
---|
34 | this.wsServer.clients.forEach((socket) => {
|
---|
35 | if (socket.isAlive === false) {
|
---|
36 | return socket.terminate();
|
---|
37 | }
|
---|
38 |
|
---|
39 | socket.isAlive = false;
|
---|
40 | socket.ping(noop);
|
---|
41 | });
|
---|
42 | }, this.server.heartbeatInterval);
|
---|
43 | }
|
---|
44 |
|
---|
45 | send(connection, message) {
|
---|
46 | // prevent cases where the server is trying to send data while connection is closing
|
---|
47 | if (connection.readyState !== 1) {
|
---|
48 | return;
|
---|
49 | }
|
---|
50 |
|
---|
51 | connection.send(message);
|
---|
52 | }
|
---|
53 |
|
---|
54 | close(connection) {
|
---|
55 | connection.close();
|
---|
56 | }
|
---|
57 |
|
---|
58 | // f should be passed the resulting connection and the connection headers
|
---|
59 | onConnection(f) {
|
---|
60 | this.wsServer.on('connection', (connection, req) => {
|
---|
61 | connection.isAlive = true;
|
---|
62 | connection.on('pong', () => {
|
---|
63 | connection.isAlive = true;
|
---|
64 | });
|
---|
65 | f(connection, req.headers);
|
---|
66 | });
|
---|
67 | }
|
---|
68 |
|
---|
69 | onConnectionClose(connection, f) {
|
---|
70 | connection.on('close', f);
|
---|
71 | }
|
---|
72 | };
|
---|