transport.js 2.4 KB

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