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.

285 lines
6.0 KiB

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