You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
991 B

4 years ago
  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. server: this.server.listeningApp,
  12. path: this.server.sockPath,
  13. });
  14. this.wsServer.on('error', (err) => {
  15. this.server.log.error(err.message);
  16. });
  17. }
  18. send(connection, message) {
  19. // prevent cases where the server is trying to send data while connection is closing
  20. if (connection.readyState !== 1) {
  21. return;
  22. }
  23. connection.send(message);
  24. }
  25. close(connection) {
  26. connection.close();
  27. }
  28. // f should be passed the resulting connection and the connection headers
  29. onConnection(f) {
  30. this.wsServer.on('connection', (connection, req) => {
  31. f(connection, req.headers);
  32. });
  33. }
  34. onConnectionClose(connection, f) {
  35. connection.on('close', f);
  36. }
  37. };