PageRenderTime 143ms CodeModel.GetById 55ms app.highlight 44ms RepoModel.GetById 31ms 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

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

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