WebsocketServer.js 1.6 KB

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