zhangjian
2023-08-07 6b009b0f6d3ef3aee97c362cebcd679d1b9088a3
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
'use strict';
 
/* eslint-disable
  class-methods-use-this
*/
const ws = require('ws');
const BaseServer = require('./BaseServer');
 
module.exports = class WebsocketServer extends BaseServer {
  constructor(server) {
    super(server);
    this.wsServer = new ws.Server({
      noServer: true,
      path: this.server.sockPath,
    });
 
    this.server.listeningApp.on('upgrade', (req, sock, head) => {
      if (!this.wsServer.shouldHandle(req)) {
        return;
      }
 
      this.wsServer.handleUpgrade(req, sock, head, (connection) => {
        this.wsServer.emit('connection', connection, req);
      });
    });
 
    this.wsServer.on('error', (err) => {
      this.server.log.error(err.message);
    });
 
    const noop = () => {};
 
    setInterval(() => {
      this.wsServer.clients.forEach((socket) => {
        if (socket.isAlive === false) {
          return socket.terminate();
        }
 
        socket.isAlive = false;
        socket.ping(noop);
      });
    }, this.server.heartbeatInterval);
  }
 
  send(connection, message) {
    // prevent cases where the server is trying to send data while connection is closing
    if (connection.readyState !== 1) {
      return;
    }
 
    connection.send(message);
  }
 
  close(connection) {
    connection.close();
  }
 
  // f should be passed the resulting connection and the connection headers
  onConnection(f) {
    this.wsServer.on('connection', (connection, req) => {
      connection.isAlive = true;
      connection.on('pong', () => {
        connection.isAlive = true;
      });
      f(connection, req.headers);
    });
  }
 
  onConnectionClose(connection, f) {
    connection.on('close', f);
  }
};