PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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. return this;
  1581. };
  1582. /**
  1583. * Queues messages when there isn't a active connection available. Once a connection has been
  1584. * established you should call the `doQueue` method to send the queued messages to the server.
  1585. *
  1586. * @param {Mixed} message The message that was originally send to the `send` method.
  1587. * @returns {io.Socket}
  1588. * @api private
  1589. */
  1590. Socket.prototype.queue = function(message){
  1591. if (!('queueStack' in this)) this.queueStack = [];
  1592. this.queueStack.push(message);
  1593. return this;
  1594. };
  1595. /**
  1596. * If there are queued messages we send all messages to the Socket.IO server and empty
  1597. * the queue.
  1598. *
  1599. * @returns {io.Socket}
  1600. * @api private
  1601. */
  1602. Socket.prototype.doQueue = function(){
  1603. if (!('queueStack' in this) || !this.queueStack.length) return this;
  1604. this.transport.send(this.queueStack);
  1605. this.queueStack = [];
  1606. return this;
  1607. };
  1608. /**
  1609. * Check if we need to use cross domain enabled transports. Cross domain would
  1610. * be a different port or different domain name.
  1611. *
  1612. * @returns {Boolean}
  1613. * @api private
  1614. */
  1615. Socket.prototype.isXDomain = function(){
  1616. var locPort = window.location.port || 80;
  1617. return this.host !== document.domain || this.options.port != locPort;
  1618. };
  1619. /**
  1620. * When the transport established an working connection the Socket.IO server it notifies us
  1621. * by calling this method so we can set the `connected` and `connecting` properties and emit
  1622. * the connection event.
  1623. *
  1624. * @api private
  1625. */
  1626. Socket.prototype.onConnect = function(){
  1627. this.connected = true;
  1628. this.connecting = false;
  1629. this.doQueue();
  1630. if (this.options.rememberTransport) this.options.document.cookie = 'socketio=' + encodeURIComponent(this.transport.type);
  1631. this.emit('connect');
  1632. };
  1633. /**
  1634. * When the transport receives new messages from the Socket.IO server it notifies us by calling
  1635. * this method with the decoded `data` it received.
  1636. *
  1637. * @param data The message from the Socket.IO server.
  1638. * @api private
  1639. */
  1640. Socket.prototype.onMessage = function(data){
  1641. this.emit('message', [data]);
  1642. };
  1643. /**
  1644. * When the transport is disconnected from the Socket.IO server it notifies us by calling
  1645. * this method. If we where connected and the `reconnect` is set we will attempt to reconnect.
  1646. *
  1647. * @api private
  1648. */
  1649. Socket.prototype.onDisconnect = function(){
  1650. var wasConnected = this.connected;
  1651. this.connected = false;
  1652. this.connecting = false;
  1653. this.queueStack = [];
  1654. if (wasConnected){
  1655. this.emit('disconnect');
  1656. if (this.options.reconnect && !this.reconnecting) this.onReconnect();
  1657. }
  1658. };
  1659. /**
  1660. * The reconnection is done using an exponential back off algorithm to prevent
  1661. * the server from being flooded with connection requests. When the transport
  1662. * is disconnected we wait until the `reconnectionDelay` finishes. We multiply
  1663. * the `reconnectionDelay` (if the previous `reconnectionDelay` was 500 it will
  1664. * be updated to 1000 and than 2000>4000>8000>16000 etc.) and tell the current
  1665. * transport to connect again. When we run out of `reconnectionAttempts` we will
  1666. * do one final attempt and loop over all enabled transport methods to see if
  1667. * other transports might work. If everything fails we emit the `reconnect_failed`
  1668. * event.
  1669. *
  1670. * @api private
  1671. */
  1672. Socket.prototype.onReconnect = function(){
  1673. this.reconnecting = true;
  1674. this.reconnectionAttempts = 0;
  1675. this.reconnectionDelay = this.options.reconnectionDelay;
  1676. var self = this
  1677. , tryTransportsOnConnectTimeout = this.options.tryTransportsOnConnectTimeout
  1678. , rememberTransport = this.options.rememberTransport;
  1679. function reset(){
  1680. if(self.connected) self.emit('reconnect',[self.transport.type,self.reconnectionAttempts]);
  1681. self.removeEvent('connect_failed', maybeReconnect).removeEvent('connect', maybeReconnect);
  1682. self.reconnecting = false;
  1683. delete self.reconnectionAttempts;
  1684. delete self.reconnectionDelay;
  1685. delete self.reconnectionTimer;
  1686. delete self.redoTransports;
  1687. self.options.tryTransportsOnConnectTimeout = tryTransportsOnConnectTimeout;
  1688. self.options.rememberTransport = rememberTransport;
  1689. return;
  1690. };
  1691. function maybeReconnect(){
  1692. if (!self.reconnecting) return;
  1693. if (!self.connected){
  1694. if (self.connecting && self.reconnecting) return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1695. if (self.reconnectionAttempts++ >= self.options.maxReconnectionAttempts){
  1696. if (!self.redoTransports){
  1697. self.on('connect_failed', maybeReconnect);
  1698. self.options.tryTransportsOnConnectTimeout = true;
  1699. self.transport = self.getTransport(self.options.transports); // override with all enabled transports
  1700. self.redoTransports = true;
  1701. self.connect();
  1702. } else {
  1703. self.emit('reconnect_failed');
  1704. reset();
  1705. }
  1706. } else {
  1707. self.reconnectionDelay *= 2; // exponential back off
  1708. self.connect();
  1709. self.emit('reconnecting', [self.reconnectionDelay,self.reconnectionAttempts]);
  1710. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1711. }
  1712. } else {
  1713. reset();
  1714. }
  1715. };
  1716. this.options.tryTransportsOnConnectTimeout = false;
  1717. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1718. this.on('connect', maybeReconnect);
  1719. };
  1720. /**
  1721. * API compatiblity
  1722. */
  1723. Socket.prototype.fire = Socket.prototype.emit;
  1724. Socket.prototype.addListener = Socket.prototype.addEvent = Socket.prototype.addEventListener = Socket.prototype.on;
  1725. Socket.prototype.removeListener = Socket.prototype.removeEventListener = Socket.prototype.removeEvent;
  1726. })();
  1727. /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
  1728. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  1729. */
  1730. var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
  1731. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  1732. // License: New BSD License
  1733. // Reference: http://dev.w3.org/html5/websockets/
  1734. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
  1735. (function() {
  1736. if (window.WebSocket) return;
  1737. var console = window.console;
  1738. if (!console || !console.log || !console.error) {
  1739. console = {log: function(){ }, error: function(){ }};
  1740. }
  1741. if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
  1742. console.error("Flash Player >= 10.0.0 is required.");
  1743. return;
  1744. }
  1745. if (location.protocol == "file:") {
  1746. console.error(
  1747. "WARNING: web-socket-js doesn't work in file:///... URL " +
  1748. "unless you set Flash Security Settings properly. " +
  1749. "Open the page via Web server i.e. http://...");
  1750. }
  1751. /**
  1752. * This class represents a faux web socket.
  1753. * @param {string} url
  1754. * @param {array or string} protocols
  1755. * @param {string} proxyHost
  1756. * @param {int} proxyPort
  1757. * @param {string} headers
  1758. */
  1759. WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
  1760. var self = this;
  1761. self.__id = WebSocket.__nextId++;
  1762. WebSocket.__instances[self.__id] = self;
  1763. self.readyState = WebSocket.CONNECTING;
  1764. self.bufferedAmount = 0;
  1765. self.__events = {};
  1766. if (!protocols) {
  1767. protocols = [];
  1768. } else if (typeof protocols == "string") {
  1769. protocols = [protocols];
  1770. }
  1771. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  1772. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  1773. setTimeout(function() {
  1774. WebSocket.__addTask(function() {
  1775. WebSocket.__flash.create(
  1776. self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
  1777. });
  1778. }, 0);
  1779. };
  1780. /**
  1781. * Send data to the web socket.
  1782. * @param {string} data The data to send to the socket.
  1783. * @return {boolean} True for success, false for failure.
  1784. */
  1785. WebSocket.prototype.send = function(data) {
  1786. if (this.readyState == WebSocket.CONNECTING) {
  1787. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  1788. }
  1789. // We use encodeURIComponent() here, because FABridge doesn't work if
  1790. // the argument includes some characters. We don't use escape() here
  1791. // because of this:
  1792. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  1793. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  1794. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  1795. // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
  1796. // additional testing.
  1797. var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
  1798. if (result < 0) { // success
  1799. return true;
  1800. } else {
  1801. this.bufferedAmount += result;
  1802. return false;
  1803. }
  1804. };
  1805. /**
  1806. * Close this web socket gracefully.
  1807. */
  1808. WebSocket.prototype.close = function() {
  1809. if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
  1810. return;
  1811. }
  1812. this.readyState = WebSocket.CLOSING;
  1813. WebSocket.__flash.close(this.__id);
  1814. };
  1815. /**
  1816. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1817. *
  1818. * @param {string} type
  1819. * @param {function} listener
  1820. * @param {boolean} useCapture
  1821. * @return void
  1822. */
  1823. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  1824. if (!(type in this.__events)) {
  1825. this.__events[type] = [];
  1826. }
  1827. this.__events[type].push(listener);
  1828. };
  1829. /**
  1830. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1831. *
  1832. * @param {string} type
  1833. * @param {function} listener
  1834. * @param {boolean} useCapture
  1835. * @return void
  1836. */
  1837. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  1838. if (!(type in this.__events)) return;
  1839. var events = this.__events[type];
  1840. for (var i = events.length - 1; i >= 0; --i) {
  1841. if (events[i] === listener) {
  1842. events.splice(i, 1);
  1843. break;
  1844. }
  1845. }
  1846. };
  1847. /**
  1848. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1849. *
  1850. * @param {Event} event
  1851. * @return void
  1852. */
  1853. WebSocket.prototype.dispatchEvent = function(event) {
  1854. var events = this.__events[event.type] || [];
  1855. for (var i = 0; i < events.length; ++i) {
  1856. events[i](event);
  1857. }
  1858. var handler = this["on" + event.type];
  1859. if (handler) handler(event);
  1860. };
  1861. /**
  1862. * Handles an event from Flash.
  1863. * @param {Object} flashEvent
  1864. */
  1865. WebSocket.prototype.__handleEvent = function(flashEvent) {
  1866. if ("readyState" in flashEvent) {
  1867. this.readyState = flashEvent.readyState;
  1868. }
  1869. if ("protocol" in flashEvent) {
  1870. this.protocol = flashEvent.protocol;
  1871. }
  1872. var jsEvent;
  1873. if (flashEvent.type == "open" || flashEvent.type == "error") {
  1874. jsEvent = this.__createSimpleEvent(flashEvent.type);
  1875. } else if (flashEvent.type == "close") {
  1876. // TODO implement jsEvent.wasClean
  1877. jsEvent = this.__createSimpleEvent("close");
  1878. } else if (flashEvent.type == "message") {
  1879. var data = decodeURIComponent(flashEvent.message);
  1880. jsEvent = this.__createMessageEvent("message", data);
  1881. } else {
  1882. throw "unknown event type: " + flashEvent.type;
  1883. }
  1884. this.dispatchEvent(jsEvent);
  1885. };
  1886. WebSocket.prototype.__createSimpleEvent = function(type) {
  1887. if (document.createEvent && window.Event) {
  1888. var event = document.createEvent("Event");
  1889. event.initEvent(type, false, false);
  1890. return event;
  1891. } else {
  1892. return {type: type, bubbles: false, cancelable: false};
  1893. }
  1894. };
  1895. WebSocket.prototype.__createMessageEvent = function(type, data) {
  1896. if (document.createEvent && window.MessageEvent && !window.opera) {
  1897. var event = document.createEvent("MessageEvent");
  1898. event.initMessageEvent("message", false, false, data, null, null, window, null);
  1899. return event;
  1900. } else {
  1901. // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
  1902. return {type: type, data: data, bubbles: false, cancelable: false};
  1903. }
  1904. };
  1905. /**
  1906. * Define the WebSocket readyState enumeration.
  1907. */
  1908. WebSocket.CONNECTING = 0;
  1909. WebSocket.OPEN = 1;
  1910. WebSocket.CLOSING = 2;
  1911. WebSocket.CLOSED = 3;
  1912. WebSocket.__flash = null;
  1913. WebSocket.__instances = {};
  1914. WebSocket.__tasks = [];
  1915. WebSocket.__nextId = 0;
  1916. /**
  1917. * Load a new flash security policy file.
  1918. * @param {string} url
  1919. */
  1920. WebSocket.loadFlashPolicyFile = function(url){
  1921. WebSocket.__addTask(function() {
  1922. WebSocket.__flash.loadManualPolicyFile(url);
  1923. });
  1924. };
  1925. /**
  1926. * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
  1927. */
  1928. WebSocket.__initialize = function() {
  1929. if (WebSocket.__flash) return;
  1930. if (WebSocket.__swfLocation) {
  1931. // For backword compatibility.
  1932. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  1933. }
  1934. if (!window.WEB_SOCKET_SWF_LOCATION) {
  1935. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  1936. return;
  1937. }
  1938. var container = document.createElement("div");
  1939. container.id = "webSocketContainer";
  1940. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  1941. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  1942. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  1943. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  1944. // the best we can do as far as we know now.
  1945. container.style.position = "absolute";
  1946. if (WebSocket.__isFlashLite()) {
  1947. container.style.left = "0px";
  1948. container.style.top = "0px";
  1949. } else {
  1950. container.style.left = "-100px";
  1951. container.style.top = "-100px";
  1952. }
  1953. var holder = document.createElement("div");
  1954. holder.id = "webSocketFlash";
  1955. container.appendChild(holder);
  1956. document.body.appendChild(container);
  1957. // See this article for hasPriority:
  1958. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  1959. swfobject.embedSWF(
  1960. WEB_SOCKET_SWF_LOCATION,
  1961. "webSocketFlash",
  1962. "1" /* width */,
  1963. "1" /* height */,
  1964. "10.0.0" /* SWF version */,
  1965. null,
  1966. null,
  1967. {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
  1968. null,
  1969. function(e) {
  1970. if (!e.success) {
  1971. console.error("[WebSocket] swfobject.embedSWF failed");
  1972. }
  1973. });
  1974. };
  1975. /**
  1976. * Called by Flash to notify JS that it's fully loaded and ready
  1977. * for communication.
  1978. */
  1979. WebSocket.__onFlashInitialized = function() {
  1980. // We need to set a timeout here to avoid round-trip calls
  1981. // to flash during the initialization process.
  1982. setTimeout(function() {
  1983. WebSocket.__flash = document.getElementById("webSocketFlash");
  1984. WebSocket.__flash.setCallerUrl(location.href);
  1985. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  1986. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  1987. WebSocket.__tasks[i]();
  1988. }
  1989. WebSocket.__tasks = [];
  1990. }, 0);
  1991. };
  1992. /**
  1993. * Called by Flash to notify WebSockets events are fired.
  1994. */
  1995. WebSocket.__onFlashEvent = function() {
  1996. setTimeout(function() {
  1997. try {
  1998. // Gets events using receiveEvents() instead of getting it from event object
  1999. // of Flash event. This is to make sure to keep message order.
  2000. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  2001. var events = WebSocket.__flash.receiveEvents();
  2002. for (var i = 0; i < events.length; ++i) {
  2003. WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
  2004. }
  2005. } catch (e) {
  2006. console.error(e);
  2007. }
  2008. }, 0);
  2009. return true;
  2010. };
  2011. // Called by Flash.
  2012. WebSocket.__log = function(message) {
  2013. console.log(decodeURIComponent(message));
  2014. };
  2015. // Called by Flash.
  2016. WebSocket.__error = function(message) {
  2017. console.error(decodeURIComponent(message));
  2018. };
  2019. WebSocket.__addTask = function(task) {
  2020. if (WebSocket.__flash) {
  2021. task();
  2022. } else {
  2023. WebSocket.__tasks.push(task);
  2024. }
  2025. };
  2026. /**
  2027. * Test if the browser is running flash lite.
  2028. * @return {boolean} True if flash lite is running, false otherwise.
  2029. */
  2030. WebSocket.__isFlashLite = function() {
  2031. if (!window.navigator || !window.navigator.mimeTypes) {
  2032. return false;
  2033. }
  2034. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  2035. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
  2036. return false;
  2037. }
  2038. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  2039. };
  2040. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  2041. if (window.addEventListener) {
  2042. window.addEventListener("load", function(){
  2043. WebSocket.__initialize();
  2044. }, false);
  2045. } else {
  2046. window.attachEvent("onload", function(){
  2047. WebSocket.__initialize();
  2048. });
  2049. }
  2050. }
  2051. })();