transport.js 2.1 KB

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