websocket.js 6.0 KB

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