PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/server/node_modules/now/include/Socket.IO/support/socket.io-client/socket.io.js

https://bitbucket.org/shinzero/betelgeuse
JavaScript | 2235 lines | 1003 code | 183 blank | 1049 comment | 232 complexity | 00f2a768eaa4b217be635d9f543fec40 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. /** Socket.IO 0.6.3 - Built with build.js */
  2. /**
  3. * socket.io-node-client
  4. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  5. * MIT Licensed
  6. */
  7. /**
  8. * @namespace
  9. */
  10. var io = this.io = {
  11. /**
  12. * Library version.
  13. */
  14. version: '0.6.3',
  15. /**
  16. * Updates the location of the WebSocketMain.swf file that is required for the Flashsocket transport.
  17. * This should only be needed if you want to load in the WebSocketMainInsecure.swf or if you want to
  18. * host the .swf file on a other server.
  19. *
  20. * @static
  21. * @deprecated Set the variable `WEB_SOCKET_SWF_LOCATION` pointing to WebSocketMain.swf
  22. * @param {String} path The path of the .swf file
  23. * @api public
  24. */
  25. setPath: function(path){
  26. if (window.console && console.error) console.error('io.setPath will be removed. Please set the variable WEB_SOCKET_SWF_LOCATION pointing to WebSocketMain.swf');
  27. this.path = /\/$/.test(path) ? path : path + '/';
  28. WEB_SOCKET_SWF_LOCATION = path + 'lib/vendor/web-socket-js/WebSocketMain.swf';
  29. }
  30. };
  31. /**
  32. * Expose Socket.IO in jQuery
  33. */
  34. if ('jQuery' in this) jQuery.io = this.io;
  35. /**
  36. * Default path to the .swf file.
  37. */
  38. if (typeof window != 'undefined'){
  39. // WEB_SOCKET_SWF_LOCATION = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cdn.socket.io/' + this.io.version + '/WebSocketMain.swf';
  40. if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined')
  41. WEB_SOCKET_SWF_LOCATION = '/socket.io/lib/vendor/web-socket-js/WebSocketMain.swf';
  42. }
  43. /**
  44. * socket.io-node-client
  45. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  46. * MIT Licensed
  47. */
  48. (function(){
  49. var io = this.io,
  50. /**
  51. * Set when the `onload` event is executed on the page. This variable is used by
  52. * `io.util.load` to detect if we need to execute the function immediately or add
  53. * it to a onload listener.
  54. *
  55. * @type {Boolean}
  56. * @api private
  57. */
  58. pageLoaded = false;
  59. /**
  60. * @namespace
  61. */
  62. io.util = {
  63. /**
  64. * Executes the given function when the page is loaded.
  65. *
  66. * Example:
  67. *
  68. * io.util.load(function(){ console.log('page loaded') });
  69. *
  70. * @param {Function} fn
  71. * @api public
  72. */
  73. load: function(fn){
  74. if (/loaded|complete/.test(document.readyState) || pageLoaded) return fn();
  75. if ('attachEvent' in window){
  76. window.attachEvent('onload', fn);
  77. } else {
  78. window.addEventListener('load', fn, false);
  79. }
  80. },
  81. /**
  82. * Defers the function untill it's the function can be executed without
  83. * blocking the load process. This is especially needed for WebKit based
  84. * browsers. If a long running connection is made before the onload event
  85. * a loading indicator spinner will be present at all times untill a
  86. * reconnect has been made.
  87. *
  88. * @param {Function} fn
  89. * @api public
  90. */
  91. defer: function(fn){
  92. if (!io.util.webkit) return fn();
  93. io.util.load(function(){
  94. setTimeout(fn,100);
  95. });
  96. },
  97. /**
  98. * Inherit the prototype methods from one constructor into another.
  99. *
  100. * Example:
  101. *
  102. * function foo(){};
  103. * foo.prototype.hello = function(){ console.log( this.words )};
  104. *
  105. * function bar(){
  106. * this.words = "Hello world";
  107. * };
  108. *
  109. * io.util.inherit(bar,foo);
  110. * var person = new bar();
  111. * person.hello();
  112. * // => "Hello World"
  113. *
  114. * @param {Constructor} ctor The constructor that needs to inherit the methods.
  115. * @param {Constructor} superCtor The constructor to inherit from.
  116. * @api public
  117. */
  118. inherit: function(ctor, superCtor){
  119. // no support for `instanceof` for now
  120. for (var i in superCtor.prototype){
  121. ctor.prototype[i] = superCtor.prototype[i];
  122. }
  123. },
  124. /**
  125. * Finds the index of item in a given Array.
  126. *
  127. * Example:
  128. *
  129. * var data = ['socket',2,3,4,'socket',5,6,7,'io'];
  130. * io.util.indexOf(data,'socket',1);
  131. * // => 4
  132. *
  133. * @param {Array} arr The array
  134. * @param item The item that we need to find
  135. * @param {Integer} from Starting point
  136. * @api public
  137. */
  138. indexOf: function(arr, item, from){
  139. for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){
  140. if (arr[i] === item) return i;
  141. }
  142. return -1;
  143. },
  144. /**
  145. * Checks if the given object is an Array.
  146. *
  147. * Example:
  148. *
  149. * io.util.isArray([]);
  150. * // => true
  151. * io.util.isArray({});
  152. * // => false
  153. *
  154. * @param obj
  155. * @api public
  156. */
  157. isArray: function(obj){
  158. return Object.prototype.toString.call(obj) === '[object Array]';
  159. },
  160. /**
  161. * Merges the properties of two objects.
  162. *
  163. * Example:
  164. *
  165. * var a = {foo:'bar'}
  166. * , b = {bar:'baz'};
  167. *
  168. * io.util.merge(a,b);
  169. * // => {foo:'bar',bar:'baz'}
  170. *
  171. * @param {Object} target The object that receives the keys
  172. * @param {Object} additional The object that supplies the keys
  173. * @api public
  174. */
  175. merge: function(target, additional){
  176. for (var i in additional)
  177. if (additional.hasOwnProperty(i))
  178. target[i] = additional[i];
  179. }
  180. };
  181. /**
  182. * Detect the Webkit platform based on the userAgent string.
  183. * This includes Mobile Webkit.
  184. *
  185. * @type {Boolean}
  186. * @api public
  187. */
  188. io.util.webkit = /webkit/i.test(navigator.userAgent);
  189. io.util.load(function(){
  190. pageLoaded = true;
  191. });
  192. })();
  193. /**
  194. * socket.io-node-client
  195. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  196. * MIT Licensed
  197. */
  198. (function(){
  199. var io = this.io,
  200. /**
  201. * Message frame for encoding and decoding responses from the Socket.IO server.
  202. *
  203. * @const
  204. * @type {String}
  205. */
  206. frame = '~m~',
  207. /**
  208. * Transforms the message to a string. If the message is an {Object} we will convert it to
  209. * a string and prefix it with the `~j~` flag to indicate that message is JSON encoded.
  210. *
  211. * Example:
  212. *
  213. * stringify({foo:"bar"});
  214. * // => "~j~{"foo":"bar"}"
  215. *
  216. * @param {String|Array|Object} message The messages that needs to be transformed to a string.
  217. * @throws {Error} When the JSON.stringify implementation is missing in the browser.
  218. * @returns {String} Message.
  219. * @api private
  220. */
  221. stringify = function(message){
  222. if (Object.prototype.toString.call(message) == '[object Object]'){
  223. if (!('JSON' in window)){
  224. var error = 'Socket.IO Error: Trying to encode as JSON, but JSON.stringify is missing.';
  225. if ('console' in window && console.error){
  226. console.error(error);
  227. } else {
  228. throw new Error(error);
  229. }
  230. return '{ "$error": "'+ error +'" }';
  231. }
  232. return '~j~' + JSON.stringify(message);
  233. } else {
  234. return String(message);
  235. }
  236. },
  237. /**
  238. * This is the transport template for all supported transport methods. It provides the
  239. * basic functionality to create a working transport for Socket.IO.
  240. *
  241. * Options:
  242. * - `timeout` Transport shutdown timeout in milliseconds, based on the heartbeat interval.
  243. *
  244. * Example:
  245. *
  246. * var transport = io.Transport.mytransport = function(){
  247. * io.Transport.apply(this, arguments);
  248. * };
  249. * io.util.inherit(transport, io.Transport);
  250. *
  251. * ... // more code here
  252. *
  253. * // connect with your new transport
  254. * var socket = new io.Socket(null,{transports:['mytransport']});
  255. *
  256. * @constructor
  257. * @param {Object} base The reference to io.Socket.
  258. * @param {Object} options The transport options.
  259. * @property {io.Socket|Object} base The reference to io.Socket.
  260. * @property {Object} options The transport options, these are used to overwrite the default options
  261. * @property {String} sessionid The sessionid of the established connection, this is only available a connection is established
  262. * @property {Boolean} connected The connection has been established.
  263. * @property {Boolean} connecting We are still connecting to the server.
  264. * @api public
  265. */
  266. Transport = io.Transport = function(base, options){
  267. this.base = base;
  268. if (this.base.oldid) {
  269. this.sessionid = this.base.oldid;
  270. }
  271. this.options = {
  272. timeout: 15000 // based on heartbeat interval default
  273. };
  274. io.util.merge(this.options, options);
  275. };
  276. /**
  277. * Send the message to the connected Socket.IO server.
  278. *
  279. * @throws {Error} When the io.Transport is inherited, it should override this method.
  280. * @api public
  281. */
  282. Transport.prototype.send = function(){
  283. throw new Error('Missing send() implementation');
  284. };
  285. /**
  286. * Establish a connection with the Socket.IO server..
  287. *
  288. * @throws {Error} When the io.Transport is inherited, it should override this method.
  289. * @api public
  290. */
  291. Transport.prototype.connect = function(){
  292. throw new Error('Missing connect() implementation');
  293. };
  294. /**
  295. * Disconnect the established connection.
  296. *
  297. * @throws {Error} When the io.Transport is inherited, it should override this method.
  298. * @api private
  299. */
  300. Transport.prototype.disconnect = function(){
  301. throw new Error('Missing disconnect() implementation');
  302. };
  303. /**
  304. * Encode the message by adding the `frame` to each message. This allows
  305. * the client so send multiple messages with only one request.
  306. *
  307. * @param {String|Array} messages Messages that need to be encoded.
  308. * @returns {String} Encoded message.
  309. * @api private
  310. */
  311. Transport.prototype.encode = function(messages){
  312. var ret = '', message;
  313. messages = io.util.isArray(messages) ? messages : [messages];
  314. for (var i = 0, l = messages.length; i < l; i++){
  315. message = messages[i] === null || messages[i] === undefined ? '' : stringify(messages[i]);
  316. ret += frame + message.length + frame + message;
  317. }
  318. return ret;
  319. };
  320. /**
  321. * Decoded the response from the Socket.IO server, as the server could send multiple
  322. * messages in one response.
  323. *
  324. * @param (String} data The response from the server that requires decoding
  325. * @returns {Array} Decoded messages.
  326. * @api private
  327. */
  328. Transport.prototype.decode = function(data){
  329. var messages = [], number, n;
  330. do {
  331. if (data.substr(0, 3) !== frame) return messages;
  332. data = data.substr(3);
  333. number = '', n = '';
  334. for (var i = 0, l = data.length; i < l; i++){
  335. n = Number(data.substr(i, 1));
  336. if (data.substr(i, 1) == n){
  337. number += n;
  338. } else {
  339. data = data.substr(number.length + frame.length);
  340. number = Number(number);
  341. break;
  342. }
  343. }
  344. messages.push(data.substr(0, number)); // here
  345. data = data.substr(number);
  346. } while(data !== '');
  347. return messages;
  348. };
  349. /**
  350. * Handles the response from the server. When a new response is received
  351. * it will automatically update the timeout, decode the message and
  352. * forwards the response to the onMessage function for further processing.
  353. *
  354. * @param {String} data Response from the server.
  355. * @api private
  356. */
  357. Transport.prototype.onData = function(data){
  358. this.setTimeout();
  359. var msgs = this.decode(data);
  360. if (msgs && msgs.length){
  361. for (var i = 0, l = msgs.length; i < l; i++){
  362. this.onMessage(msgs[i]);
  363. }
  364. }
  365. };
  366. /**
  367. * All the transports have a dedicated timeout to detect if
  368. * the connection is still alive. We clear the existing timer
  369. * and set new one each time this function is called. When the
  370. * timeout does occur it will call the `onTimeout` method.
  371. *
  372. * @api private
  373. */
  374. Transport.prototype.setTimeout = function(){
  375. var self = this;
  376. if (this.timeout) clearTimeout(this.timeout);
  377. this.timeout = setTimeout(function(){
  378. self.onTimeout();
  379. }, this.options.timeout);
  380. };
  381. /**
  382. * Disconnect from the Socket.IO server when a timeout occurs.
  383. *
  384. * @api private
  385. */
  386. Transport.prototype.onTimeout = function(){
  387. this.onDisconnect();
  388. };
  389. /**
  390. * After the response from the server has been parsed to individual
  391. * messages we need to decode them using the the Socket.IO message
  392. * protocol: <https://github.com/learnboost/socket.io-node/>.
  393. *
  394. * When a message is received we check if a session id has been set,
  395. * if the session id is missing we can assume that the received message
  396. * contains the sessionid of the connection.
  397. * When a message is prefixed with `~h~` we dispatch it our heartbeat
  398. * processing method `onHeartbeat` with the content of the heartbeat.
  399. *
  400. * When the message is prefixed with `~j~` we can assume that the contents
  401. * of the message is JSON encoded, so we parse the message and notify
  402. * the base of the new message.
  403. *
  404. * If none of the above, we consider it just a plain text message and
  405. * notify the base of the new message.
  406. *
  407. * @param {String} message A decoded message from the server.
  408. * @api private
  409. */
  410. Transport.prototype.onMessage = function(message){
  411. if (!this.sessionid){
  412. this.sessionid = message;
  413. this.base.oldid = message;
  414. this.onConnect();
  415. } else if (message.substr(0, 3) == '~h~'){
  416. this.onHeartbeat(message.substr(3));
  417. } else if (message.substr(0, 3) == '~j~'){
  418. this.base.onMessage(JSON.parse(message.substr(3)));
  419. } else {
  420. this.base.onMessage(message);
  421. }
  422. },
  423. /**
  424. * Send the received heartbeat message back to server. So the server
  425. * knows we are still connected.
  426. *
  427. * @param {String} heartbeat Heartbeat response from the server.
  428. * @api private
  429. */
  430. Transport.prototype.onHeartbeat = function(heartbeat){
  431. this.send('~h~' + heartbeat); // echo
  432. };
  433. /**
  434. * Notifies the base when a connection to the Socket.IO server has
  435. * been established. And it starts the connection `timeout` timer.
  436. *
  437. * @api private
  438. */
  439. Transport.prototype.onConnect = function(){
  440. this.connected = true;
  441. this.connecting = false;
  442. this.base.onConnect();
  443. this.setTimeout();
  444. };
  445. /**
  446. * Notifies the base when the connection with the Socket.IO server
  447. * has been disconnected.
  448. *
  449. * @api private
  450. */
  451. Transport.prototype.onDisconnect = function(){
  452. this.connecting = false;
  453. this.connected = false;
  454. this.sessionid = null;
  455. this.base.onDisconnect();
  456. };
  457. /**
  458. * Generates a connection url based on the Socket.IO URL Protocol.
  459. * See <https://github.com/learnboost/socket.io-node/> for more details.
  460. *
  461. * @returns {String} Connection url
  462. * @api private
  463. */
  464. Transport.prototype.prepareUrl = function(){
  465. return (this.base.options.secure ? 'https' : 'http')
  466. + '://' + this.base.host
  467. + ':' + this.base.options.port
  468. + '/' + this.base.options.resource
  469. + '/' + this.type
  470. + (this.sessionid ? ('/' + this.sessionid) :
  471. (this.base.oldid ? '/' + this.base.oldid : '/'));
  472. };
  473. })();
  474. /**
  475. * socket.io-node-client
  476. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  477. * MIT Licensed
  478. */
  479. (function(){
  480. var io = this.io,
  481. /**
  482. * A small stub function that will be used to reduce memory leaks.
  483. *
  484. * @type {Function}
  485. * @api private
  486. */
  487. empty = new Function,
  488. /**
  489. * We preform a small feature detection to see if `Cross Origin Resource Sharing`
  490. * is supported in the `XMLHttpRequest` object, so we can use it for cross domain requests.
  491. *
  492. * @type {Boolean}
  493. * @api private
  494. */
  495. XMLHttpRequestCORS = (function(){
  496. if (!('XMLHttpRequest' in window)) return false;
  497. // CORS feature detection
  498. var a = new XMLHttpRequest();
  499. return a.withCredentials != undefined;
  500. })(),
  501. /**
  502. * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
  503. *
  504. * @param {Boolean} [xdomain] Create a request that can be used cross domain.
  505. * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest we will return that.
  506. * @api private
  507. */
  508. request = function(xdomain){
  509. if ('XDomainRequest' in window && xdomain) return new XDomainRequest();
  510. if ('XMLHttpRequest' in window && (!xdomain || XMLHttpRequestCORS)) return new XMLHttpRequest();
  511. if (!xdomain){
  512. try {
  513. var a = new ActiveXObject('MSXML2.XMLHTTP');
  514. return a;
  515. } catch(e){}
  516. try {
  517. var b = new ActiveXObject('Microsoft.XMLHTTP');
  518. return b;
  519. } catch(e){}
  520. }
  521. return false;
  522. },
  523. /**
  524. * This is the base for XHR based transports, the `XHR-Polling` and the `XHR-multipart`
  525. * transports will extend this class.
  526. *
  527. * @constructor
  528. * @extends {io.Transport}
  529. * @property {Array} sendBuffer Used to queue up messages so they can be send as one request.
  530. * @api public
  531. */
  532. XHR = io.Transport.XHR = function(){
  533. io.Transport.apply(this, arguments);
  534. this.sendBuffer = [];
  535. };
  536. io.util.inherit(XHR, io.Transport);
  537. /**
  538. * Establish a connection
  539. *
  540. * @returns {Transport}
  541. * @api public
  542. */
  543. XHR.prototype.connect = function(){
  544. this.get();
  545. return this;
  546. };
  547. /**
  548. * Check if we need to send data to the Socket.IO server, if we have data in our buffer
  549. * we encode it and forward it to the sendIORequest method.
  550. *
  551. * @api private
  552. */
  553. XHR.prototype.checkSend = function(){
  554. if (!this.posting && this.sendBuffer.length){
  555. var encoded = this.encode(this.sendBuffer);
  556. this.sendBuffer = [];
  557. this.sendIORequest(encoded);
  558. }
  559. };
  560. /**
  561. * Send data to the Socket.IO server.
  562. *
  563. * @param data The message
  564. * @returns {Transport}
  565. * @api public
  566. */
  567. XHR.prototype.send = function(data){
  568. if (io.util.isArray(data)){
  569. this.sendBuffer.push.apply(this.sendBuffer, data);
  570. } else {
  571. this.sendBuffer.push(data);
  572. }
  573. this.checkSend();
  574. return this;
  575. };
  576. /**
  577. * Posts a encoded message to the Socket.IO server.
  578. *
  579. * @param {String} data A encoded message.
  580. * @api private
  581. */
  582. XHR.prototype.sendIORequest = function(data){
  583. var self = this;
  584. this.posting = true;
  585. this.sendXHR = this.request('send', 'POST');
  586. this.sendXHR.onreadystatechange = function(){
  587. var status;
  588. if (self.sendXHR.readyState == 4){
  589. self.sendXHR.onreadystatechange = empty;
  590. try { status = self.sendXHR.status; } catch(e){}
  591. self.posting = false;
  592. if (status == 200){
  593. self.checkSend();
  594. } else {
  595. self.onDisconnect();
  596. }
  597. }
  598. };
  599. this.sendXHR.send('data=' + encodeURIComponent(data));
  600. };
  601. /**
  602. * Disconnect the established connection.
  603. *
  604. * @returns {Transport}.
  605. * @api public
  606. */
  607. XHR.prototype.disconnect = function(){
  608. // send disconnection signal
  609. this.onDisconnect();
  610. return this;
  611. };
  612. /**
  613. * Handle the disconnect request.
  614. *
  615. * @api private
  616. */
  617. XHR.prototype.onDisconnect = function(){
  618. if (this.xhr){
  619. this.xhr.onreadystatechange = empty;
  620. try {
  621. this.xhr.abort();
  622. } catch(e){}
  623. this.xhr = null;
  624. }
  625. if (this.sendXHR){
  626. this.sendXHR.onreadystatechange = empty;
  627. try {
  628. this.sendXHR.abort();
  629. } catch(e){}
  630. this.sendXHR = null;
  631. }
  632. this.sendBuffer = [];
  633. io.Transport.prototype.onDisconnect.call(this);
  634. };
  635. /**
  636. * Generates a configured XHR request
  637. *
  638. * @param {String} url The url that needs to be requested.
  639. * @param {String} method The method the request should use.
  640. * @param {Boolean} multipart Do a multipart XHR request
  641. * @returns {XMLHttpRequest}
  642. * @api private
  643. */
  644. XHR.prototype.request = function(url, method, multipart){
  645. var req = request(this.base.isXDomain());
  646. if (multipart) req.multipart = true;
  647. req.open(method || 'GET', this.prepareUrl() + (url ? '/' + url : ''));
  648. if (method == 'POST' && 'setRequestHeader' in req){
  649. req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
  650. }
  651. return req;
  652. };
  653. /**
  654. * Check if the XHR transports are supported
  655. *
  656. * @param {Boolean} xdomain Check if we support cross domain requests.
  657. * @returns {Boolean}
  658. * @api public
  659. */
  660. XHR.check = function(xdomain){
  661. try {
  662. if (request(xdomain)) return true;
  663. } catch(e){}
  664. return false;
  665. };
  666. /**
  667. * Check if the XHR transport supports corss domain requests.
  668. *
  669. * @returns {Boolean}
  670. * @api public
  671. */
  672. XHR.xdomainCheck = function(){
  673. return XHR.check(true);
  674. };
  675. XHR.request = request;
  676. })();
  677. /**
  678. * socket.io-node-client
  679. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  680. * MIT Licensed
  681. */
  682. (function(){
  683. var io = this.io,
  684. /**
  685. * The WebSocket transport uses the HTML5 WebSocket API to establish an persistent
  686. * connection with the Socket.IO server. This transport will also be inherited by the
  687. * FlashSocket fallback as it provides a API compatible polyfill for the WebSockets.
  688. *
  689. * @constructor
  690. * @extends {io.Transport}
  691. * @api public
  692. */
  693. WS = io.Transport.websocket = function(){
  694. io.Transport.apply(this, arguments);
  695. };
  696. io.util.inherit(WS, io.Transport);
  697. /**
  698. * The transport type, you use this to identify which transport was chosen.
  699. *
  700. * @type {String}
  701. * @api public
  702. */
  703. WS.prototype.type = 'websocket';
  704. /**
  705. * Initializes a new `WebSocket` connection with the Socket.IO server. We attach
  706. * all the appropriate listeners to handle the responses from the server.
  707. *
  708. * @returns {Transport}
  709. * @api public
  710. */
  711. WS.prototype.connect = function(){
  712. var self = this;
  713. this.socket = new WebSocket(this.prepareUrl());
  714. this.socket.onmessage = function(ev){ self.onData(ev.data); };
  715. this.socket.onclose = function(ev){ self.onDisconnect(); };
  716. this.socket.onerror = function(e){ self.onError(e); };
  717. return this;
  718. };
  719. /**
  720. * Send a message to the Socket.IO server. The message will automatically be encoded
  721. * in the correct message format.
  722. *
  723. * @returns {Transport}
  724. * @api public
  725. */
  726. WS.prototype.send = function(data){
  727. if (this.socket) this.socket.send(this.encode(data));
  728. return this;
  729. };
  730. /**
  731. * Disconnect the established `WebSocket` connection.
  732. *
  733. * @returns {Transport}
  734. * @api public
  735. */
  736. WS.prototype.disconnect = function(){
  737. if (this.socket) this.socket.close();
  738. return this;
  739. };
  740. /**
  741. * Handle the errors that `WebSocket` might be giving when we
  742. * are attempting to connect or send messages.
  743. *
  744. * @param {Error} e The error.
  745. * @api private
  746. */
  747. WS.prototype.onError = function(e){
  748. this.base.emit('error', [e]);
  749. };
  750. /**
  751. * Generate a `WebSocket` compatible URL based on the options
  752. * the user supplied in our Socket.IO base.
  753. *
  754. * @returns {String} Connection url
  755. * @api private
  756. */
  757. WS.prototype.prepareUrl = function(){
  758. return (this.base.options.secure ? 'wss' : 'ws')
  759. + '://' + this.base.host
  760. + ':' + this.base.options.port
  761. + '/' + this.base.options.resource
  762. + '/' + this.type
  763. + (this.sessionid ? ('/' + this.sessionid) :
  764. (this.base.oldid ? '/' + this.base.oldid : ''));
  765. };
  766. /**
  767. * Checks if the browser has support for native `WebSockets` and that
  768. * it's not the polyfill created for the FlashSocket transport.
  769. *
  770. * @return {Boolean}
  771. * @api public
  772. */
  773. WS.check = function(){
  774. // we make sure WebSocket is not confounded with a previously loaded flash WebSocket
  775. return 'WebSocket' in window && WebSocket.prototype && ( WebSocket.prototype.send && !!WebSocket.prototype.send.toString().match(/native/i)) && typeof WebSocket !== "undefined";
  776. };
  777. /**
  778. * Check if the `WebSocket` transport support cross domain communications.
  779. *
  780. *@returns {Boolean}
  781. * @api public
  782. */
  783. WS.xdomainCheck = function(){
  784. return true;
  785. };
  786. })();
  787. /**
  788. * socket.io-node-client
  789. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  790. * MIT Licensed
  791. */
  792. (function(){
  793. var io = this.io,
  794. /**
  795. * The Flashsocket transport. This is a API wrapper for the HTML5 WebSocket specification.
  796. * It uses a .swf file to communicate with the server. If you want to serve the .swf file
  797. * from a other server than where the Socket.IO script is coming from you need to use the
  798. * insecure version of the .swf. More information about this can be found on the github page.
  799. *
  800. * @constructor
  801. * @extends {io.Transport.websocket}
  802. * @api public
  803. */
  804. Flashsocket = io.Transport.flashsocket = function(){
  805. io.Transport.websocket.apply(this, arguments);
  806. };
  807. io.util.inherit(Flashsocket, io.Transport.websocket);
  808. /**
  809. * The transport type, you use this to identify which transport was chosen.
  810. *
  811. * @type {String}
  812. * @api public
  813. */
  814. Flashsocket.prototype.type = 'flashsocket';
  815. /**
  816. * Disconnect the established `Flashsocket` connection. This is done by adding a new
  817. * task to the Flashsocket. The rest will be handled off by the `WebSocket` transport.
  818. *
  819. * @returns {Transport}
  820. * @api public
  821. */
  822. Flashsocket.prototype.connect = function(){
  823. var self = this, args = arguments;
  824. WebSocket.__addTask(function(){
  825. io.Transport.websocket.prototype.connect.apply(self, args);
  826. });
  827. return this;
  828. };
  829. /**
  830. * Sends a message to the Socket.IO server. This is done by adding a new
  831. * task to the Flashsocket. The rest will be handled off by the `WebSocket` transport.
  832. *
  833. * @returns {Transport}
  834. * @api public
  835. */
  836. Flashsocket.prototype.send = function(){
  837. var self = this, args = arguments;
  838. WebSocket.__addTask(function(){
  839. io.Transport.websocket.prototype.send.apply(self, args);
  840. });
  841. return this;
  842. };
  843. /**
  844. * Check if the Flashsocket transport is supported as it requires that the Adobe Flash Player
  845. * plugin version `10.0.0` or greater is installed. And also check if the polyfill is correctly
  846. * loaded.
  847. *
  848. * @returns {Boolean}
  849. * @api public
  850. */
  851. Flashsocket.check = function(){
  852. if (typeof WebSocket == 'undefined' || !('__addTask' in WebSocket) || !swfobject) return false;
  853. return swfobject.hasFlashPlayerVersion("10.0.0");
  854. };
  855. /**
  856. * Check if the Flashsocket transport can be used as cross domain / cross origin transport.
  857. * Because we can't see which type (secure or insecure) of .swf is used we will just return true.
  858. *
  859. * @returns {Boolean}
  860. * @api public
  861. */
  862. Flashsocket.xdomainCheck = function(){
  863. return true;
  864. };
  865. })();
  866. /**
  867. * socket.io-node-client
  868. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  869. * MIT Licensed
  870. */
  871. (function(){
  872. var io = this.io,
  873. /**
  874. * The HTMLFile transport creates a `forever iframe` based transport
  875. * for Internet Explorer. Regular forever iframe implementations will
  876. * continuously trigger the browsers buzy indicators. If the forever iframe
  877. * is created inside a `htmlfile` these indicators will not be trigged.
  878. *
  879. * @constructor
  880. * @extends {io.Transport.XHR}
  881. * @api public
  882. */
  883. HTMLFile = io.Transport.htmlfile = function(){
  884. io.Transport.XHR.apply(this, arguments);
  885. };
  886. io.util.inherit(HTMLFile, io.Transport.XHR);
  887. /**
  888. * The transport type, you use this to identify which transport was chosen.
  889. *
  890. * @type {String}
  891. * @api public
  892. */
  893. HTMLFile.prototype.type = 'htmlfile';
  894. /**
  895. * Starts the HTMLFile data stream for incoming messages. And registers a
  896. * onunload event listener so the HTMLFile will be destroyed.
  897. *
  898. * @api private
  899. */
  900. HTMLFile.prototype.get = function(){
  901. var self = this;
  902. this.open();
  903. window.attachEvent('onunload', function(){ self.destroy(); });
  904. };
  905. /**
  906. * Creates a new ActiveX `htmlfile` with a forever loading iframe
  907. * that can be used to listen to messages. Inside the generated
  908. * `htmlfile` a reference will be made to the HTMLFile transport.
  909. *
  910. * @api private
  911. */
  912. HTMLFile.prototype.open = function(){
  913. this.doc = new ActiveXObject('htmlfile');
  914. this.doc.open();
  915. this.doc.write('<html></html>');
  916. this.doc.parentWindow.s = this;
  917. this.doc.close();
  918. var iframeC = this.doc.createElement('div');
  919. this.doc.body.appendChild(iframeC);
  920. this.iframe = this.doc.createElement('iframe');
  921. iframeC.appendChild(this.iframe);
  922. this.iframe.src = this.prepareUrl() + '/' + (+ new Date);
  923. };
  924. /**
  925. * The Socket.IO server will write script tags inside the forever
  926. * iframe, this function will be used as callback for the incoming
  927. * information.
  928. *
  929. * @param {String} data The message
  930. * @param {document} doc Reference to the context
  931. * @api private
  932. */
  933. HTMLFile.prototype._ = function(data, doc){
  934. this.onData(data);
  935. var script = doc.getElementsByTagName('script')[0];
  936. script.parentNode.removeChild(script);
  937. };
  938. /**
  939. * Destroy the established connection, iframe and `htmlfile`.
  940. * And calls the `CollectGarbage` function of Internet Explorer
  941. * to release the memory.
  942. *
  943. * @api private
  944. */
  945. HTMLFile.prototype.destroy = function(){
  946. if (this.iframe){
  947. try {
  948. this.iframe.src = 'about:blank';
  949. } catch(e){}
  950. this.doc = null;
  951. CollectGarbage();
  952. }
  953. };
  954. /**
  955. * Disconnects the established connection.
  956. *
  957. * @returns {Transport} Chaining.
  958. * @api public
  959. */
  960. HTMLFile.prototype.disconnect = function(){
  961. this.destroy();
  962. return io.Transport.XHR.prototype.disconnect.call(this);
  963. };
  964. /**
  965. * Checks if the browser supports this transport. The browser
  966. * must have an `ActiveXObject` implementation.
  967. *
  968. * @return {Boolean}
  969. * @api public
  970. */
  971. HTMLFile.check = function(){
  972. if ('ActiveXObject' in window){
  973. try {
  974. var a = new ActiveXObject('htmlfile');
  975. return a && io.Transport.XHR.check();
  976. } catch(e){}
  977. }
  978. return false;
  979. };
  980. /**
  981. * Check if cross domain requests are supported.
  982. *
  983. * @returns {Boolean}
  984. * @api public
  985. */
  986. HTMLFile.xdomainCheck = function(){
  987. // we can probably do handling for sub-domains, we should test that it's cross domain but a subdomain here
  988. return false;
  989. };
  990. })();
  991. /**
  992. * socket.io-node-client
  993. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  994. * MIT Licensed
  995. */
  996. (function(){
  997. var io = this.io,
  998. /**
  999. * The XHR-Multipart transport uses the a multipart XHR connection to
  1000. * stream in the data from the Socket.IO server
  1001. *
  1002. * @constructor
  1003. * @extends {io.Transport.XHR}
  1004. * @api public
  1005. */
  1006. XHRMultipart = io.Transport['xhr-multipart'] = function(){
  1007. io.Transport.XHR.apply(this, arguments);
  1008. };
  1009. io.util.inherit(XHRMultipart, io.Transport.XHR);
  1010. /**
  1011. * The transport type, you use this to identify which transport was chosen.
  1012. *
  1013. * @type {String}
  1014. * @api public
  1015. */
  1016. XHRMultipart.prototype.type = 'xhr-multipart';
  1017. /**
  1018. * Starts the multipart stream for incomming messages.
  1019. *
  1020. * @api private
  1021. */
  1022. XHRMultipart.prototype.get = function(){
  1023. var self = this;
  1024. this.xhr = this.request('', 'GET', true);
  1025. this.xhr.onreadystatechange = function(){
  1026. if (self.xhr.readyState == 4) self.onData(self.xhr.responseText);
  1027. };
  1028. this.xhr.send(null);
  1029. };
  1030. /**
  1031. * Checks if browser supports this transport.
  1032. *
  1033. * @return {Boolean}
  1034. * @api public
  1035. */
  1036. XHRMultipart.check = function(){
  1037. return 'XMLHttpRequest' in window && 'prototype' in XMLHttpRequest && 'multipart' in XMLHttpRequest.prototype;
  1038. };
  1039. /**
  1040. * Check if cross domain requests are supported.
  1041. *
  1042. * @returns {Boolean}
  1043. * @api public
  1044. */
  1045. XHRMultipart.xdomainCheck = function(){
  1046. return true;
  1047. };
  1048. })();
  1049. /**
  1050. * socket.io-node-client
  1051. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1052. * MIT Licensed
  1053. */
  1054. (function(){
  1055. var io = this.io,
  1056. /**
  1057. * A small stub function that will be used to reduce memory leaks.
  1058. *
  1059. * @type {Function}
  1060. * @api private
  1061. */
  1062. empty = new Function(),
  1063. /**
  1064. * The XHR-polling transport uses long polling XHR requests to create a
  1065. * "persistent" connection with the server.
  1066. *
  1067. * @constructor
  1068. * @extends {io.Transport.XHR}
  1069. * @api public
  1070. */
  1071. XHRPolling = io.Transport['xhr-polling'] = function(){
  1072. io.Transport.XHR.apply(this, arguments);
  1073. };
  1074. io.util.inherit(XHRPolling, io.Transport.XHR);
  1075. /**
  1076. * The transport type, you use this to identify which transport was chosen.
  1077. *
  1078. * @type {string}
  1079. * @api public
  1080. */
  1081. XHRPolling.prototype.type = 'xhr-polling';
  1082. /**
  1083. * Establish a connection, for iPhone and Android this will be done once the page
  1084. * is loaded.
  1085. *
  1086. * @returns {Transport} Chaining.
  1087. * @api public
  1088. */
  1089. XHRPolling.prototype.connect = function(){
  1090. var self = this;
  1091. io.util.defer(function(){ io.Transport.XHR.prototype.connect.call(self) });
  1092. return false;
  1093. };
  1094. /**
  1095. * Starts a XHR request to wait for incoming messages.
  1096. *
  1097. * @api private
  1098. */
  1099. XHRPolling.prototype.get = function(){
  1100. var self = this;
  1101. this.xhr = this.request(+ new Date, 'GET');
  1102. this.xhr.onreadystatechange = function(){
  1103. var status;
  1104. if (self.xhr.readyState == 4){
  1105. self.xhr.onreadystatechange = empty;
  1106. try { status = self.xhr.status; } catch(e){}
  1107. if (status == 200){
  1108. self.onData(self.xhr.responseText);
  1109. self.get();
  1110. } else {
  1111. self.onDisconnect();
  1112. }
  1113. }
  1114. };
  1115. this.xhr.send(null);
  1116. };
  1117. /**
  1118. * Checks if browser supports this transport.
  1119. *
  1120. * @return {Boolean}
  1121. * @api public
  1122. */
  1123. XHRPolling.check = function(){
  1124. return io.Transport.XHR.check();
  1125. };
  1126. /**
  1127. * Check if cross domain requests are supported
  1128. *
  1129. * @returns {Boolean}
  1130. * @api public
  1131. */
  1132. XHRPolling.xdomainCheck = function(){
  1133. return io.Transport.XHR.xdomainCheck();
  1134. };
  1135. })();
  1136. /**
  1137. * socket.io-node-client
  1138. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1139. * MIT Licensed
  1140. */
  1141. (function(){
  1142. var io = this.io,
  1143. /**
  1144. * The JSONP transport creates an persistent connection by dynamically
  1145. * inserting a script tag in the page. This script tag will receive the
  1146. * information of the Socket.IO server. When new information is received
  1147. * it creates a new script tag for the new data stream.
  1148. *
  1149. * @constructor
  1150. * @extends {io.Transport.xhr-polling}
  1151. * @api public
  1152. */
  1153. JSONPPolling = io.Transport['jsonp-polling'] = function(){
  1154. io.Transport.XHR.apply(this, arguments);
  1155. this.insertAt = document.getElementsByTagName('script')[0];
  1156. this.index = io.JSONP.length;
  1157. io.JSONP.push(this);
  1158. };
  1159. io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
  1160. /**
  1161. * A list of all JSONPolling transports, this is used for by
  1162. * the Socket.IO server to distribute the callbacks.
  1163. *
  1164. * @type {Array}
  1165. * @api private
  1166. */
  1167. io.JSONP = [];
  1168. /**
  1169. * The transport type, you use this to identify which transport was chosen.
  1170. *
  1171. * @type {String}
  1172. * @api public
  1173. */
  1174. JSONPPolling.prototype.type = 'jsonp-polling';
  1175. /**
  1176. * Posts a encoded message to the Socket.IO server using an iframe.
  1177. * The iframe is used because script tags can create POST based requests.
  1178. * The iframe is positioned outside of the view so the user does not
  1179. * notice it's existence.
  1180. *
  1181. * @param {String} data A encoded message.
  1182. * @api private
  1183. */
  1184. JSONPPolling.prototype.sendIORequest = function(data){
  1185. var self = this;
  1186. if (!('form' in this)){
  1187. var form = document.createElement('FORM'),
  1188. area = document.createElement('TEXTAREA'),
  1189. id = this.iframeId = 'socket_io_iframe_' + this.index,
  1190. iframe;
  1191. form.style.position = 'absolute';
  1192. form.style.top = '-1000px';
  1193. form.style.left = '-1000px';
  1194. form.target = id;
  1195. form.method = 'POST';
  1196. form.action = this.prepareUrl() + '/' + (+new Date) + '/' + this.index;
  1197. area.name = 'data';
  1198. form.appendChild(area);
  1199. this.insertAt.parentNode.insertBefore(form, this.insertAt);
  1200. document.body.appendChild(form);
  1201. this.form = form;
  1202. this.area = area;
  1203. }
  1204. function complete(){
  1205. initIframe();
  1206. self.posting = false;
  1207. self.checkSend();
  1208. };
  1209. function initIframe(){
  1210. if (self.iframe){
  1211. self.form.removeChild(self.iframe);
  1212. }
  1213. try {
  1214. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  1215. iframe = document.createElement('<iframe name="'+ self.iframeId +'">');
  1216. } catch(e){
  1217. iframe = document.createElement('iframe');
  1218. iframe.name = self.iframeId;
  1219. }
  1220. iframe.id = self.iframeId;
  1221. self.form.appendChild(iframe);
  1222. self.iframe = iframe;
  1223. };
  1224. initIframe();
  1225. this.posting = true;
  1226. this.area.value = data;
  1227. try {
  1228. this.form.submit();
  1229. } catch(e){}
  1230. if (this.iframe.attachEvent){
  1231. iframe.onreadystatechange = function(){
  1232. if (self.iframe.readyState == 'complete') complete();
  1233. };
  1234. } else {
  1235. this.iframe.onload = complete;
  1236. }
  1237. };
  1238. /**
  1239. * Creates a new JSONP poll that can be used to listen
  1240. * for messages from the Socket.IO server.
  1241. *
  1242. * @api private
  1243. */
  1244. JSONPPolling.prototype.get = function(){
  1245. var self = this,
  1246. script = document.createElement('SCRIPT');
  1247. if (this.script){
  1248. this.script.parentNode.removeChild(this.script);
  1249. this.script = null;
  1250. }
  1251. script.async = true;
  1252. script.src = this.prepareUrl() + '/' + (+new Date) + '/' + this.index;
  1253. script.onerror = function(){
  1254. self.onDisconnect();
  1255. };
  1256. this.insertAt.parentNode.insertBefore(script, this.insertAt);
  1257. this.script = script;
  1258. };
  1259. /**
  1260. * Callback function for the incoming message stream from the Socket.IO server.
  1261. *
  1262. * @param {String} data The message
  1263. * @param {document} doc Reference to the context
  1264. * @api private
  1265. */
  1266. JSONPPolling.prototype._ = function(){
  1267. this.onData.apply(this, arguments);
  1268. this.get();
  1269. return this;
  1270. };
  1271. /**
  1272. * Checks if browser supports this transport.
  1273. *
  1274. * @return {Boolean}
  1275. * @api public
  1276. */
  1277. JSONPPolling.check = function(){
  1278. return true;
  1279. };
  1280. /**
  1281. * Check if cross domain requests are supported
  1282. *
  1283. * @returns {Boolean}
  1284. * @api public
  1285. */
  1286. JSONPPolling.xdomainCheck = function(){
  1287. return true;
  1288. };
  1289. })();
  1290. /**
  1291. * socket.io-node-client
  1292. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1293. * MIT Licensed
  1294. */
  1295. (function(){
  1296. var io = this.io;
  1297. /**
  1298. * Create a new `Socket.IO client` which can establish a persisted
  1299. * connection with a Socket.IO enabled server.
  1300. *
  1301. * Options:
  1302. * - `secure` Use secure connections, defaulting to false.
  1303. * - `document` Reference to the document object to retrieve and set cookies, defaulting to document.
  1304. * - `port` The port where the Socket.IO server listening on, defaulting to location.port.
  1305. * - `resource` The path or namespace on the server where the Socket.IO requests are intercepted, defaulting to 'socket.io'.
  1306. * - `transports` A ordered list with the available transports, defaulting to all transports.
  1307. * - `transportOption` A {Object} containing the options for each transport. The key of the object should reflect
  1308. * name of the transport and the value a {Object} with the options.
  1309. * - `connectTimeout` The duration in milliseconds that a transport has to establish a working connection, defaulting to 5000.
  1310. * - `tryTransportsOnConnectTimeout` Should we attempt other transport methods when the connectTimeout occurs, defaulting to true.
  1311. * - `reconnect` Should reconnection happen automatically, defaulting to true.
  1312. * - `reconnectionDelay` The delay in milliseconds before we attempt to establish a working connection. This value will
  1313. * increase automatically using a exponential back off algorithm. Defaulting to 500.
  1314. * - `maxReconnectionAttempts` Number of attempts we should make before seizing the reconnect operation, defaulting to 10.
  1315. * - `rememberTransport` Should the successfully connected transport be remembered in a cookie, defaulting to true.
  1316. *
  1317. * Examples:
  1318. *
  1319. * Create client with the default settings.
  1320. *
  1321. * var socket = new io.Socket();
  1322. * socket.connect();
  1323. * socket.on('message', function(msg){
  1324. * console.log('Received message: ' + msg );
  1325. * });
  1326. * socket.on('connect', function(){
  1327. * socket.send('Hello from client');
  1328. * });
  1329. *
  1330. * Create a connection with server on a different port and host.
  1331. *
  1332. * var socket = new io.Socket('http://example.com',{port:1337});
  1333. *
  1334. * @constructor
  1335. * @exports Socket as io.Socket
  1336. * @param {String} [host] The host where the Socket.IO server is located, it defaults to the host that runs the page.
  1337. * @param {Objects} [options] The options that will configure the Socket.IO client.
  1338. * @property {String} host The supplied host arguments or the host that page runs.
  1339. * @property {Object} options The passed options combined with the defaults.
  1340. * @property {Boolean} connected Whether the socket is connected or not.
  1341. * @property {Boolean} connecting Whether the socket is connecting or not.
  1342. * @property {Boolean} reconnecting Whether the socket is reconnecting or not.
  1343. * @property {Object} transport The selected transport instance.
  1344. * @api public
  1345. */
  1346. var Socket = io.Socket = function(host, options){
  1347. this.host = host || document.domain;
  1348. this.options = {
  1349. secure: false,
  1350. document: document,
  1351. port: document.location.port || 80,
  1352. resource: 'socket.io',
  1353. transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
  1354. transportOptions: {
  1355. 'xhr-polling': {
  1356. timeout: 25000 // based on polling duration default
  1357. },
  1358. 'jsonp-polling': {
  1359. timeout: 25000
  1360. }
  1361. },
  1362. connectTimeout: 5000,
  1363. tryTransportsOnConnectTimeout: true,
  1364. reconnect: true,
  1365. reconnectionDelay: 500,
  1366. maxReconnectionAttempts: 3,
  1367. rememberTransport: true
  1368. };
  1369. io.util.merge(this.options, options);
  1370. this.connected = false;
  1371. this.connecting = false;
  1372. this.reconnecting = false;
  1373. this.events = {};
  1374. this.transport = this.getTransport();
  1375. if (!this.transport && 'console' in window) console.error('No transport available');
  1376. };
  1377. /**
  1378. * Find an available transport based on the options supplied in the constructor. For example if the
  1379. * `rememberTransport` option was set we will only connect with the previous successfully connected transport.
  1380. * The supplied transports can be overruled if the `override` argument is supplied.
  1381. *
  1382. * Example:
  1383. *
  1384. * Override the existing transports.
  1385. *
  1386. * var socket = new io.Socket();
  1387. * socket.getTransport(['jsonp-polling','websocket']);
  1388. * // returns the json-polling transport because it's availabe in all browsers.
  1389. *
  1390. * @param {Array} [override] A ordered list with transports that should be used instead of the options.transports.
  1391. * @returns {Null|Transport} The available transport.
  1392. * @api private
  1393. */
  1394. Socket.prototype.getTransport = function(override){
  1395. var transports = override || this.options.transports, match;
  1396. if (this.options.rememberTransport && !override){
  1397. match = this.options.document.cookie.match('(?:^|;)\\s*socketio=([^;]*)');
  1398. if (match){
  1399. this.rememberedTransport = true;
  1400. transports = [decodeURIComponent(match[1])];
  1401. }
  1402. }
  1403. for (var i = 0, transport; transport = transports[i]; i++){
  1404. if (io.Transport[transport]
  1405. && io.Transport[transport].check()
  1406. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())){
  1407. return new io.Transport[transport](this, this.options.transportOptions[transport] || {});
  1408. }
  1409. }
  1410. return null;
  1411. };
  1412. /**
  1413. * Establish a new connection with the Socket.IO server. This is done using the selected transport by the
  1414. * getTransport method. If the `connectTimeout` and the `tryTransportsOnConnectTimeout` options are set
  1415. * the client will keep trying to connect to the server using a different transports when the timeout occurs.
  1416. *
  1417. * Example:
  1418. *
  1419. * Create a Socket.IO client with a connect callback (We assume we have the WebSocket transport avaliable).
  1420. *
  1421. * var socket = new io.Socket();
  1422. * socket.connect(function(transport){
  1423. * console.log("Connected to server using the " + socket.transport.type + " transport.");
  1424. * });
  1425. * // => "Connected to server using the WebSocket transport."
  1426. *
  1427. * @param {Function} [fn] Callback.
  1428. * @returns {io.Socket}
  1429. * @api public
  1430. */
  1431. Socket.prototype.connect = function(fn){
  1432. if (this.transport && !this.connected){
  1433. if (this.connecting) this.disconnect(true);
  1434. this.connecting = true;
  1435. this.emit('connecting', [this.transport.type]);
  1436. this.transport.connect();
  1437. if (this.options.connectTimeout){
  1438. var self = this;
  1439. this.connectTimeoutTimer = setTimeout(function(){
  1440. if (!self.connected){
  1441. self.disconnect(true);
  1442. if (self.options.tryTransportsOnConnectTimeout && !self.rememberedTransport){
  1443. if(!self.remainingTransports) self.remainingTransports = self.options.transports.slice(0);
  1444. var transports = self.remainingTransports;
  1445. while(transports.length > 0 && transports.splice(0,1)[0] != self.transport.type){}
  1446. if(transports.length){
  1447. self.transport = self.getTransport(transports);
  1448. self.connect();
  1449. }
  1450. }
  1451. if(!self.remainingTransports || self.remainingTransports.length == 0) self.emit('connect_failed');
  1452. }
  1453. if(self.remainingTransports && self.remainingTransports.length == 0) delete self.remainingTransports;
  1454. }, this.options.connectTimeout);
  1455. }
  1456. }
  1457. if (fn && typeof fn == 'function') this.once('connect',fn);
  1458. return this;
  1459. };
  1460. /**
  1461. * Sends the data to the Socket.IO server. If there isn't a connection to the server
  1462. * the data will be forwarded to the queue.
  1463. *
  1464. * @param {Mixed} data The data that needs to be send to the Socket.IO server.
  1465. * @returns {io.Socket}
  1466. * @api public
  1467. */
  1468. Socket.prototype.send = function(data){
  1469. if (!this.transport || !this.transport.connected) return this.queue(data);
  1470. this.transport.send(data);
  1471. return this;
  1472. };
  1473. /**
  1474. * Disconnect the established connect.
  1475. *
  1476. * @param {Boolean} [soft] A soft disconnect will keep the reconnect settings enabled.
  1477. * @returns {io.Socket}
  1478. * @api public
  1479. */
  1480. Socket.prototype.disconnect = function(){
  1481. if (this.connectTimeoutTimer) clearTimeout(this.connectTimeoutTimer);
  1482. this.options.reconnect = false;
  1483. this.transport.disconnect();
  1484. return this;
  1485. };
  1486. /**
  1487. * Adds a new eventListener for the given event.
  1488. *
  1489. * Example:
  1490. *
  1491. * var socket = new io.Socket();
  1492. * socket.on("connect", function(transport){
  1493. * console.log("Connected to server using the " + socket.transport.type + " transport.");
  1494. * });
  1495. * // => "Connected to server using the WebSocket transport."
  1496. *
  1497. * @param {String} name The name of the event.
  1498. * @param {Function} fn The function that is called once the event is emitted.
  1499. * @returns {io.Socket}
  1500. * @api public
  1501. */
  1502. Socket.prototype.on = function(name, fn){
  1503. if (!(name in this.events)) this.events[name] = [];
  1504. this.events[name].push(fn);
  1505. return this;
  1506. };
  1507. /**
  1508. * Adds a one time listener, the listener will be removed after the event is emitted.
  1509. *
  1510. * Example:
  1511. *
  1512. * var socket = new io.Socket();
  1513. * socket.once("custom:event", function(){
  1514. * console.log("I should only log once.");
  1515. * });
  1516. * socket.emit("custom:event");
  1517. * socket.emit("custom:event");
  1518. * // => "I should only log once."
  1519. *
  1520. * @param {String} name The name of the event.
  1521. * @param {Function} fn The function that is called once the event is emitted.
  1522. * @returns {io.Socket}
  1523. * @api public
  1524. */
  1525. Socket.prototype.once = function(name, fn){
  1526. var self = this
  1527. , once = function(){
  1528. self.removeEvent(name, once);
  1529. fn.apply(self, arguments);
  1530. };
  1531. once.ref = fn;
  1532. self.on(name, once);
  1533. return this;
  1534. };
  1535. /**
  1536. * Emit a event to all listeners.
  1537. *
  1538. * Example:
  1539. *
  1540. * var socket = new io.Socket();
  1541. * socket.on("custom:event", function(){
  1542. * console.log("Emitted a custom:event");
  1543. * });
  1544. * socket.emit("custom:event");
  1545. * // => "Emitted a custom:event"
  1546. *
  1547. * @param {String} name The name of the event.
  1548. * @param {Array} args Arguments for the event.
  1549. * @returns {io.Socket}
  1550. * @api private
  1551. */
  1552. Socket.prototype.emit = function(name, args){
  1553. if (name in this.events){
  1554. var events = this.events[name].concat();
  1555. for (var i = 0, ii = events.length; i < ii; i++)
  1556. events[i].apply(this, args === undefined ? [] : args);
  1557. }
  1558. return this;
  1559. };
  1560. /**
  1561. * Removes a event listener from the listener array for the specified event.
  1562. *
  1563. * Example:
  1564. *
  1565. * var socket = new io.Socket()
  1566. * , event = function(){};
  1567. * socket.on("connect", event);
  1568. * socket.removeEvent("connect", event);
  1569. *
  1570. * @param {String} name The name of the event.
  1571. * @param {Function} fn The function that is called once the event is emitted.
  1572. * @returns {io.Socket}
  1573. * @api public
  1574. */
  1575. Socket.prototype.removeEvent = function(name, fn){
  1576. if (name in this.events){
  1577. for (var a = 0, l = this.events[name].length; a < l; a++)
  1578. if (this.events[name][a] == fn || this.events[name][a].ref && this.events[name][a].ref == fn) this.events[name].splice(a, 1);
  1579. }
  1580. retur

Large files files are truncated, but you can click here to view the full file