websocket.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.WebSocket = void 0;
  4. const transport_1 = require("../transport");
  5. const debug_1 = require("debug");
  6. const debug = (0, debug_1.default)("engine:ws");
  7. class WebSocket extends transport_1.Transport {
  8. /**
  9. * WebSocket transport
  10. *
  11. * @param req
  12. * @api public
  13. */
  14. constructor(req) {
  15. super(req);
  16. this.writable = false;
  17. this.perMessageDeflate = null;
  18. }
  19. /**
  20. * Transport name
  21. *
  22. * @api public
  23. */
  24. get name() {
  25. return "websocket";
  26. }
  27. /**
  28. * Advertise upgrade support.
  29. *
  30. * @api public
  31. */
  32. get handlesUpgrades() {
  33. return true;
  34. }
  35. /**
  36. * Advertise framing support.
  37. *
  38. * @api public
  39. */
  40. get supportsFraming() {
  41. return true;
  42. }
  43. /**
  44. * Writes a packet payload.
  45. *
  46. * @param {Array} packets
  47. * @api private
  48. */
  49. send(packets) {
  50. const packet = packets.shift();
  51. if (typeof packet === "undefined") {
  52. this.writable = true;
  53. this.emit("drain");
  54. return;
  55. }
  56. // always creates a new object since ws modifies it
  57. const opts = {};
  58. if (packet.options) {
  59. opts.compress = packet.options.compress;
  60. }
  61. const send = data => {
  62. const isBinary = typeof data !== "string";
  63. const compress = this.perMessageDeflate &&
  64. Buffer.byteLength(data) > this.perMessageDeflate.threshold;
  65. debug('writing "%s"', data);
  66. this.writable = false;
  67. this.socket.send(data, isBinary, compress);
  68. this.send(packets);
  69. };
  70. if (packet.options && typeof packet.options.wsPreEncoded === "string") {
  71. send(packet.options.wsPreEncoded);
  72. }
  73. else {
  74. this.parser.encodePacket(packet, this.supportsBinary, send);
  75. }
  76. }
  77. /**
  78. * Closes the transport.
  79. *
  80. * @api private
  81. */
  82. doClose(fn) {
  83. debug("closing");
  84. fn && fn();
  85. // call fn first since socket.close() immediately emits a "close" event
  86. this.socket.close();
  87. }
  88. }
  89. exports.WebSocket = WebSocket;