You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
1.9 KiB

  1. /**
  2. * Module dependencies.
  3. */
  4. var Transport = require('../transport')
  5. , parser = require('engine.io-parser')
  6. , debug = require('debug')('engine:ws')
  7. /**
  8. * Export the constructor.
  9. */
  10. module.exports = WebSocket;
  11. /**
  12. * WebSocket transport
  13. *
  14. * @param {http.ServerRequest}
  15. * @api public
  16. */
  17. function WebSocket (req) {
  18. Transport.call(this, req);
  19. var self = this;
  20. this.socket = req.websocket;
  21. this.socket.on('message', this.onData.bind(this));
  22. this.socket.once('close', this.onClose.bind(this));
  23. this.socket.on('error', this.onError.bind(this));
  24. this.socket.on('headers', function (headers) {
  25. self.emit('headers', headers);
  26. });
  27. this.writable = true;
  28. };
  29. /**
  30. * Inherits from Transport.
  31. */
  32. WebSocket.prototype.__proto__ = Transport.prototype;
  33. /**
  34. * Transport name
  35. *
  36. * @api public
  37. */
  38. WebSocket.prototype.name = 'websocket';
  39. /**
  40. * Advertise upgrade support.
  41. *
  42. * @api public
  43. */
  44. WebSocket.prototype.handlesUpgrades = true;
  45. /**
  46. * Advertise framing support.
  47. *
  48. * @api public
  49. */
  50. WebSocket.prototype.supportsFraming = true;
  51. /**
  52. * Processes the incoming data.
  53. *
  54. * @param {String} encoded packet
  55. * @api private
  56. */
  57. WebSocket.prototype.onData = function (data) {
  58. debug('received "%s"', data);
  59. Transport.prototype.onData.call(this, data);
  60. };
  61. /**
  62. * Writes a packet payload.
  63. *
  64. * @param {Array} packets
  65. * @api private
  66. */
  67. WebSocket.prototype.send = function (packets) {
  68. var self = this;
  69. for (var i = 0, l = packets.length; i < l; i++) {
  70. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  71. debug('writing "%s"', data);
  72. self.writable = false;
  73. self.socket.send(data, function (err){
  74. if (err) return self.onError('write error', err.stack);
  75. self.writable = true;
  76. self.emit('drain');
  77. });
  78. });
  79. }
  80. };
  81. /**
  82. * Closes the transport.
  83. *
  84. * @api private
  85. */
  86. WebSocket.prototype.doClose = function (fn) {
  87. debug('closing');
  88. this.socket.close();
  89. fn && fn();
  90. };