websocket.js 6.3 KB

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