websocket.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. */
  13. constructor(req) {
  14. super(req);
  15. this.writable = false;
  16. this.perMessageDeflate = null;
  17. }
  18. /**
  19. * Transport name
  20. */
  21. get name() {
  22. return "websocket";
  23. }
  24. /**
  25. * Advertise upgrade support.
  26. */
  27. get handlesUpgrades() {
  28. return true;
  29. }
  30. /**
  31. * Writes a packet payload.
  32. *
  33. * @param {Array} packets
  34. * @private
  35. */
  36. send(packets) {
  37. this.writable = false;
  38. for (let i = 0; i < packets.length; i++) {
  39. const packet = packets[i];
  40. const isLast = i + 1 === packets.length;
  41. const send = (data) => {
  42. const isBinary = typeof data !== "string";
  43. const compress = this.perMessageDeflate &&
  44. Buffer.byteLength(data) > this.perMessageDeflate.threshold;
  45. debug('writing "%s"', data);
  46. this.socket.send(data, isBinary, compress);
  47. if (isLast) {
  48. this.emit("drain");
  49. this.writable = true;
  50. this.emit("ready");
  51. }
  52. };
  53. if (packet.options && typeof packet.options.wsPreEncoded === "string") {
  54. send(packet.options.wsPreEncoded);
  55. }
  56. else {
  57. this.parser.encodePacket(packet, this.supportsBinary, send);
  58. }
  59. }
  60. }
  61. /**
  62. * Closes the transport.
  63. *
  64. * @private
  65. */
  66. doClose(fn) {
  67. debug("closing");
  68. fn && fn();
  69. // call fn first since socket.end() immediately emits a "close" event
  70. this.socket.end();
  71. }
  72. }
  73. exports.WebSocket = WebSocket;