Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

websocket.js 6.2KB

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