websocket.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. this.writable = false;
  51. for (let i = 0; i < packets.length; i++) {
  52. const packet = packets[i];
  53. const isLast = i + 1 === packets.length;
  54. const send = (data) => {
  55. const isBinary = typeof data !== "string";
  56. const compress = this.perMessageDeflate &&
  57. Buffer.byteLength(data) > this.perMessageDeflate.threshold;
  58. debug('writing "%s"', data);
  59. this.socket.send(data, isBinary, compress);
  60. if (isLast) {
  61. this.writable = true;
  62. this.emit("drain");
  63. }
  64. };
  65. if (packet.options && typeof packet.options.wsPreEncoded === "string") {
  66. send(packet.options.wsPreEncoded);
  67. }
  68. else {
  69. this.parser.encodePacket(packet, this.supportsBinary, send);
  70. }
  71. }
  72. }
  73. /**
  74. * Closes the transport.
  75. *
  76. * @api private
  77. */
  78. doClose(fn) {
  79. debug("closing");
  80. fn && fn();
  81. // call fn first since socket.end() immediately emits a "close" event
  82. this.socket.end();
  83. }
  84. }
  85. exports.WebSocket = WebSocket;