transport.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const EventEmitter = require("events");
  2. const parser = require("engine.io-parser");
  3. const debug = require("debug")("engine:transport");
  4. /**
  5. * Noop function.
  6. *
  7. * @api private
  8. */
  9. function noop() {}
  10. class Transport extends EventEmitter {
  11. /**
  12. * Transport constructor.
  13. *
  14. * @param {http.IncomingMessage} request
  15. * @api public
  16. */
  17. constructor(req) {
  18. super();
  19. this.readyState = "open";
  20. this.discarded = false;
  21. }
  22. /**
  23. * Flags the transport as discarded.
  24. *
  25. * @api private
  26. */
  27. discard() {
  28. this.discarded = true;
  29. }
  30. /**
  31. * Called with an incoming HTTP request.
  32. *
  33. * @param {http.IncomingMessage} request
  34. * @api private
  35. */
  36. onRequest(req) {
  37. debug("setting request");
  38. this.req = req;
  39. }
  40. /**
  41. * Closes the transport.
  42. *
  43. * @api private
  44. */
  45. close(fn) {
  46. if ("closed" === this.readyState || "closing" === this.readyState) return;
  47. this.readyState = "closing";
  48. this.doClose(fn || noop);
  49. }
  50. /**
  51. * Called with a transport error.
  52. *
  53. * @param {String} message error
  54. * @param {Object} error description
  55. * @api private
  56. */
  57. onError(msg, desc) {
  58. if (this.listeners("error").length) {
  59. const err = new Error(msg);
  60. err.type = "TransportError";
  61. err.description = desc;
  62. this.emit("error", err);
  63. } else {
  64. debug("ignored transport error %s (%s)", msg, desc);
  65. }
  66. }
  67. /**
  68. * Called with parsed out a packets from the data stream.
  69. *
  70. * @param {Object} packet
  71. * @api private
  72. */
  73. onPacket(packet) {
  74. this.emit("packet", packet);
  75. }
  76. /**
  77. * Called with the encoded packet data.
  78. *
  79. * @param {String} data
  80. * @api private
  81. */
  82. onData(data) {
  83. this.onPacket(parser.decodePacket(data));
  84. }
  85. /**
  86. * Called upon transport close.
  87. *
  88. * @api private
  89. */
  90. onClose() {
  91. this.readyState = "closed";
  92. this.emit("close");
  93. }
  94. }
  95. module.exports = Transport;