transport.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { decodePacket } from "engine.io-parser";
  2. import { Emitter } from "@socket.io/component-emitter";
  3. import { installTimerFunctions } from "./util.js";
  4. import debugModule from "debug"; // debug()
  5. const debug = debugModule("engine.io-client:transport"); // debug()
  6. export class Transport extends Emitter {
  7. /**
  8. * Transport abstract constructor.
  9. *
  10. * @param {Object} options.
  11. * @api private
  12. */
  13. constructor(opts) {
  14. super();
  15. this.writable = false;
  16. installTimerFunctions(this, opts);
  17. this.opts = opts;
  18. this.query = opts.query;
  19. this.readyState = "";
  20. this.socket = opts.socket;
  21. }
  22. /**
  23. * Emits an error.
  24. *
  25. * @param {String} str
  26. * @return {Transport} for chaining
  27. * @api protected
  28. */
  29. onError(msg, desc) {
  30. const err = new Error(msg);
  31. // @ts-ignore
  32. err.type = "TransportError";
  33. // @ts-ignore
  34. err.description = desc;
  35. super.emit("error", err);
  36. return this;
  37. }
  38. /**
  39. * Opens the transport.
  40. *
  41. * @api public
  42. */
  43. open() {
  44. if ("closed" === this.readyState || "" === this.readyState) {
  45. this.readyState = "opening";
  46. this.doOpen();
  47. }
  48. return this;
  49. }
  50. /**
  51. * Closes the transport.
  52. *
  53. * @api public
  54. */
  55. close() {
  56. if ("opening" === this.readyState || "open" === this.readyState) {
  57. this.doClose();
  58. this.onClose();
  59. }
  60. return this;
  61. }
  62. /**
  63. * Sends multiple packets.
  64. *
  65. * @param {Array} packets
  66. * @api public
  67. */
  68. send(packets) {
  69. if ("open" === this.readyState) {
  70. this.write(packets);
  71. }
  72. else {
  73. // this might happen if the transport was silently closed in the beforeunload event handler
  74. debug("transport is not open, discarding packets");
  75. }
  76. }
  77. /**
  78. * Called upon open
  79. *
  80. * @api protected
  81. */
  82. onOpen() {
  83. this.readyState = "open";
  84. this.writable = true;
  85. super.emit("open");
  86. }
  87. /**
  88. * Called with data.
  89. *
  90. * @param {String} data
  91. * @api protected
  92. */
  93. onData(data) {
  94. const packet = decodePacket(data, this.socket.binaryType);
  95. this.onPacket(packet);
  96. }
  97. /**
  98. * Called with a decoded packet.
  99. *
  100. * @api protected
  101. */
  102. onPacket(packet) {
  103. super.emit("packet", packet);
  104. }
  105. /**
  106. * Called upon close.
  107. *
  108. * @api protected
  109. */
  110. onClose() {
  111. this.readyState = "closed";
  112. super.emit("close");
  113. }
  114. }