websocket.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /**
  2. * Module dependencies.
  3. */
  4. var Transport = require('../transport');
  5. var parser = require('engine.io-parser');
  6. var parseqs = require('parseqs');
  7. var inherit = require('component-inherit');
  8. var yeast = require('yeast');
  9. var debug = require('debug')('engine.io-client:websocket');
  10. var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
  11. var NodeWebSocket;
  12. if (typeof window === 'undefined') {
  13. try {
  14. NodeWebSocket = require('ws');
  15. } catch (e) { }
  16. }
  17. /**
  18. * Get either the `WebSocket` or `MozWebSocket` globals
  19. * in the browser or try to resolve WebSocket-compatible
  20. * interface exposed by `ws` for Node-like environment.
  21. */
  22. var WebSocket = BrowserWebSocket;
  23. if (!WebSocket && typeof window === 'undefined') {
  24. WebSocket = NodeWebSocket;
  25. }
  26. /**
  27. * Module exports.
  28. */
  29. module.exports = WS;
  30. /**
  31. * WebSocket transport constructor.
  32. *
  33. * @api {Object} connection options
  34. * @api public
  35. */
  36. function WS (opts) {
  37. var forceBase64 = (opts && opts.forceBase64);
  38. if (forceBase64) {
  39. this.supportsBinary = false;
  40. }
  41. this.perMessageDeflate = opts.perMessageDeflate;
  42. this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
  43. this.protocols = opts.protocols;
  44. if (!this.usingBrowserWebSocket) {
  45. WebSocket = NodeWebSocket;
  46. }
  47. Transport.call(this, opts);
  48. }
  49. /**
  50. * Inherits from Transport.
  51. */
  52. inherit(WS, Transport);
  53. /**
  54. * Transport name.
  55. *
  56. * @api public
  57. */
  58. WS.prototype.name = 'websocket';
  59. /*
  60. * WebSockets support binary
  61. */
  62. WS.prototype.supportsBinary = true;
  63. /**
  64. * Opens socket.
  65. *
  66. * @api private
  67. */
  68. WS.prototype.doOpen = function () {
  69. if (!this.check()) {
  70. // let probe timeout
  71. return;
  72. }
  73. var uri = this.uri();
  74. var protocols = this.protocols;
  75. var opts = {
  76. agent: this.agent,
  77. perMessageDeflate: this.perMessageDeflate
  78. };
  79. // SSL options for Node.js client
  80. opts.pfx = this.pfx;
  81. opts.key = this.key;
  82. opts.passphrase = this.passphrase;
  83. opts.cert = this.cert;
  84. opts.ca = this.ca;
  85. opts.ciphers = this.ciphers;
  86. opts.rejectUnauthorized = this.rejectUnauthorized;
  87. if (this.extraHeaders) {
  88. opts.headers = this.extraHeaders;
  89. }
  90. if (this.localAddress) {
  91. opts.localAddress = this.localAddress;
  92. }
  93. try {
  94. this.ws = this.usingBrowserWebSocket ? (protocols ? new WebSocket(uri, protocols) : new WebSocket(uri)) : new WebSocket(uri, protocols, opts);
  95. } catch (err) {
  96. return this.emit('error', err);
  97. }
  98. if (this.ws.binaryType === undefined) {
  99. this.supportsBinary = false;
  100. }
  101. if (this.ws.supports && this.ws.supports.binary) {
  102. this.supportsBinary = true;
  103. this.ws.binaryType = 'nodebuffer';
  104. } else {
  105. this.ws.binaryType = 'arraybuffer';
  106. }
  107. this.addEventListeners();
  108. };
  109. /**
  110. * Adds event listeners to the socket
  111. *
  112. * @api private
  113. */
  114. WS.prototype.addEventListeners = function () {
  115. var self = this;
  116. this.ws.onopen = function () {
  117. self.onOpen();
  118. };
  119. this.ws.onclose = function () {
  120. self.onClose();
  121. };
  122. this.ws.onmessage = function (ev) {
  123. self.onData(ev.data);
  124. };
  125. this.ws.onerror = function (e) {
  126. self.onError('websocket error', e);
  127. };
  128. };
  129. /**
  130. * Writes data to socket.
  131. *
  132. * @param {Array} array of packets.
  133. * @api private
  134. */
  135. WS.prototype.write = function (packets) {
  136. var self = this;
  137. this.writable = false;
  138. // encodePacket efficient as it uses WS framing
  139. // no need for encodePayload
  140. var total = packets.length;
  141. for (var i = 0, l = total; i < l; i++) {
  142. (function (packet) {
  143. parser.encodePacket(packet, self.supportsBinary, function (data) {
  144. if (!self.usingBrowserWebSocket) {
  145. // always create a new object (GH-437)
  146. var opts = {};
  147. if (packet.options) {
  148. opts.compress = packet.options.compress;
  149. }
  150. if (self.perMessageDeflate) {
  151. var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length;
  152. if (len < self.perMessageDeflate.threshold) {
  153. opts.compress = false;
  154. }
  155. }
  156. }
  157. // Sometimes the websocket has already been closed but the browser didn't
  158. // have a chance of informing us about it yet, in that case send will
  159. // throw an error
  160. try {
  161. if (self.usingBrowserWebSocket) {
  162. // TypeError is thrown when passing the second argument on Safari
  163. self.ws.send(data);
  164. } else {
  165. self.ws.send(data, opts);
  166. }
  167. } catch (e) {
  168. debug('websocket closed before onclose event');
  169. }
  170. --total || done();
  171. });
  172. })(packets[i]);
  173. }
  174. function done () {
  175. self.emit('flush');
  176. // fake drain
  177. // defer to next tick to allow Socket to clear writeBuffer
  178. setTimeout(function () {
  179. self.writable = true;
  180. self.emit('drain');
  181. }, 0);
  182. }
  183. };
  184. /**
  185. * Called upon close
  186. *
  187. * @api private
  188. */
  189. WS.prototype.onClose = function () {
  190. Transport.prototype.onClose.call(this);
  191. };
  192. /**
  193. * Closes socket.
  194. *
  195. * @api private
  196. */
  197. WS.prototype.doClose = function () {
  198. if (typeof this.ws !== 'undefined') {
  199. this.ws.close();
  200. }
  201. };
  202. /**
  203. * Generates uri for connection.
  204. *
  205. * @api private
  206. */
  207. WS.prototype.uri = function () {
  208. var query = this.query || {};
  209. var schema = this.secure ? 'wss' : 'ws';
  210. var port = '';
  211. // avoid port if default for schema
  212. if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
  213. ('ws' === schema && Number(this.port) !== 80))) {
  214. port = ':' + this.port;
  215. }
  216. // append timestamp to URI
  217. if (this.timestampRequests) {
  218. query[this.timestampParam] = yeast();
  219. }
  220. // communicate binary support capabilities
  221. if (!this.supportsBinary) {
  222. query.b64 = 1;
  223. }
  224. query = parseqs.encode(query);
  225. // prepend ? to query
  226. if (query.length) {
  227. query = '?' + query;
  228. }
  229. var ipv6 = this.hostname.indexOf(':') !== -1;
  230. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  231. };
  232. /**
  233. * Feature detection for WebSocket.
  234. *
  235. * @return {Boolean} whether this transport is available.
  236. * @api public
  237. */
  238. WS.prototype.check = function () {
  239. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  240. };