WebsocketServer.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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((socket) => {
  28. if (socket.isAlive === false) {
  29. return socket.terminate();
  30. }
  31. socket.isAlive = false;
  32. socket.ping(noop);
  33. });
  34. }, this.server.heartbeatInterval);
  35. }
  36. send(connection, message) {
  37. // prevent cases where the server is trying to send data while connection is closing
  38. if (connection.readyState !== 1) {
  39. return;
  40. }
  41. connection.send(message);
  42. }
  43. close(connection) {
  44. connection.close();
  45. }
  46. // f should be passed the resulting connection and the connection headers
  47. onConnection(f) {
  48. this.wsServer.on('connection', (connection, req) => {
  49. connection.isAlive = true;
  50. connection.on('pong', () => {
  51. connection.isAlive = true;
  52. });
  53. f(connection, req.headers);
  54. });
  55. }
  56. onConnectionClose(connection, f) {
  57. connection.on('close', f);
  58. }
  59. };