socket.io-0.6.js 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  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. this.options = {
  269. timeout: 15000 // based on heartbeat interval default
  270. };
  271. io.util.merge(this.options, options);
  272. };
  273. /**
  274. * Send the message to the connected Socket.IO server.
  275. *
  276. * @throws {Error} When the io.Transport is inherited, it should override this method.
  277. * @api public
  278. */
  279. Transport.prototype.send = function(){
  280. throw new Error('Missing send() implementation');
  281. };
  282. /**
  283. * Establish a connection with the Socket.IO server..
  284. *
  285. * @throws {Error} When the io.Transport is inherited, it should override this method.
  286. * @api public
  287. */
  288. Transport.prototype.connect = function(){
  289. throw new Error('Missing connect() implementation');
  290. };
  291. /**
  292. * Disconnect the established connection.
  293. *
  294. * @throws {Error} When the io.Transport is inherited, it should override this method.
  295. * @api private
  296. */
  297. Transport.prototype.disconnect = function(){
  298. throw new Error('Missing disconnect() implementation');
  299. };
  300. /**
  301. * Encode the message by adding the `frame` to each message. This allows
  302. * the client so send multiple messages with only one request.
  303. *
  304. * @param {String|Array} messages Messages that need to be encoded.
  305. * @returns {String} Encoded message.
  306. * @api private
  307. */
  308. Transport.prototype.encode = function(messages){
  309. var ret = '', message;
  310. messages = io.util.isArray(messages) ? messages : [messages];
  311. for (var i = 0, l = messages.length; i < l; i++){
  312. message = messages[i] === null || messages[i] === undefined ? '' : stringify(messages[i]);
  313. ret += frame + message.length + frame + message;
  314. }
  315. return ret;
  316. };
  317. /**
  318. * Decoded the response from the Socket.IO server, as the server could send multiple
  319. * messages in one response.
  320. *
  321. * @param (String} data The response from the server that requires decoding
  322. * @returns {Array} Decoded messages.
  323. * @api private
  324. */
  325. Transport.prototype.decode = function(data){
  326. var messages = [], number, n;
  327. do {
  328. if (data.substr(0, 3) !== frame) return messages;
  329. data = data.substr(3);
  330. number = '', n = '';
  331. for (var i = 0, l = data.length; i < l; i++){
  332. n = Number(data.substr(i, 1));
  333. if (data.substr(i, 1) == n){
  334. number += n;
  335. } else {
  336. data = data.substr(number.length + frame.length);
  337. number = Number(number);
  338. break;
  339. }
  340. }
  341. messages.push(data.substr(0, number)); // here
  342. data = data.substr(number);
  343. } while(data !== '');
  344. return messages;
  345. };
  346. /**
  347. * Handles the response from the server. When a new response is received
  348. * it will automatically update the timeout, decode the message and
  349. * forwards the response to the onMessage function for further processing.
  350. *
  351. * @param {String} data Response from the server.
  352. * @api private
  353. */
  354. Transport.prototype.onData = function(data){
  355. this.setTimeout();
  356. var msgs = this.decode(data);
  357. if (msgs && msgs.length){
  358. for (var i = 0, l = msgs.length; i < l; i++){
  359. this.onMessage(msgs[i]);
  360. }
  361. }
  362. };
  363. /**
  364. * All the transports have a dedicated timeout to detect if
  365. * the connection is still alive. We clear the existing timer
  366. * and set new one each time this function is called. When the
  367. * timeout does occur it will call the `onTimeout` method.
  368. *
  369. * @api private
  370. */
  371. Transport.prototype.setTimeout = function(){
  372. var self = this;
  373. if (this.timeout) clearTimeout(this.timeout);
  374. this.timeout = setTimeout(function(){
  375. self.onTimeout();
  376. }, this.options.timeout);
  377. };
  378. /**
  379. * Disconnect from the Socket.IO server when a timeout occurs.
  380. *
  381. * @api private
  382. */
  383. Transport.prototype.onTimeout = function(){
  384. this.onDisconnect();
  385. };
  386. /**
  387. * After the response from the server has been parsed to individual
  388. * messages we need to decode them using the the Socket.IO message
  389. * protocol: <https://github.com/learnboost/socket.io-node/>.
  390. *
  391. * When a message is received we check if a session id has been set,
  392. * if the session id is missing we can assume that the received message
  393. * contains the sessionid of the connection.
  394. * When a message is prefixed with `~h~` we dispatch it our heartbeat
  395. * processing method `onHeartbeat` with the content of the heartbeat.
  396. *
  397. * When the message is prefixed with `~j~` we can assume that the contents
  398. * of the message is JSON encoded, so we parse the message and notify
  399. * the base of the new message.
  400. *
  401. * If none of the above, we consider it just a plain text message and
  402. * notify the base of the new message.
  403. *
  404. * @param {String} message A decoded message from the server.
  405. * @api private
  406. */
  407. Transport.prototype.onMessage = function(message){
  408. if (!this.sessionid){
  409. this.sessionid = message;
  410. this.onConnect();
  411. } else if (message.substr(0, 3) == '~h~'){
  412. this.onHeartbeat(message.substr(3));
  413. } else if (message.substr(0, 3) == '~j~'){
  414. this.base.onMessage(JSON.parse(message.substr(3)));
  415. } else {
  416. this.base.onMessage(message);
  417. }
  418. },
  419. /**
  420. * Send the received heartbeat message back to server. So the server
  421. * knows we are still connected.
  422. *
  423. * @param {String} heartbeat Heartbeat response from the server.
  424. * @api private
  425. */
  426. Transport.prototype.onHeartbeat = function(heartbeat){
  427. this.send('~h~' + heartbeat); // echo
  428. };
  429. /**
  430. * Notifies the base when a connection to the Socket.IO server has
  431. * been established. And it starts the connection `timeout` timer.
  432. *
  433. * @api private
  434. */
  435. Transport.prototype.onConnect = function(){
  436. this.connected = true;
  437. this.connecting = false;
  438. this.base.onConnect();
  439. this.setTimeout();
  440. };
  441. /**
  442. * Notifies the base when the connection with the Socket.IO server
  443. * has been disconnected.
  444. *
  445. * @api private
  446. */
  447. Transport.prototype.onDisconnect = function(){
  448. this.connecting = false;
  449. this.connected = false;
  450. this.sessionid = null;
  451. this.base.onDisconnect();
  452. };
  453. /**
  454. * Generates a connection url based on the Socket.IO URL Protocol.
  455. * See <https://github.com/learnboost/socket.io-node/> for more details.
  456. *
  457. * @returns {String} Connection url
  458. * @api private
  459. */
  460. Transport.prototype.prepareUrl = function(){
  461. return (this.base.options.secure ? 'https' : 'http')
  462. + '://' + this.base.host
  463. + ':' + this.base.options.port
  464. + '/' + this.base.options.resource
  465. + '/' + this.type
  466. + (this.sessionid ? ('/' + this.sessionid) : '/');
  467. };
  468. })();
  469. /**
  470. * socket.io-node-client
  471. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  472. * MIT Licensed
  473. */
  474. (function(){
  475. var io = this.io,
  476. /**
  477. * A small stub function that will be used to reduce memory leaks.
  478. *
  479. * @type {Function}
  480. * @api private
  481. */
  482. empty = new Function,
  483. /**
  484. * We preform a small feature detection to see if `Cross Origin Resource Sharing`
  485. * is supported in the `XMLHttpRequest` object, so we can use it for cross domain requests.
  486. *
  487. * @type {Boolean}
  488. * @api private
  489. */
  490. XMLHttpRequestCORS = (function(){
  491. if (!('XMLHttpRequest' in window)) return false;
  492. // CORS feature detection
  493. var a = new XMLHttpRequest();
  494. return a.withCredentials != undefined;
  495. })(),
  496. /**
  497. * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
  498. *
  499. * @param {Boolean} [xdomain] Create a request that can be used cross domain.
  500. * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest we will return that.
  501. * @api private
  502. */
  503. request = function(xdomain){
  504. if ('XDomainRequest' in window && xdomain) return new XDomainRequest();
  505. if ('XMLHttpRequest' in window && (!xdomain || XMLHttpRequestCORS)) return new XMLHttpRequest();
  506. if (!xdomain){
  507. try {
  508. var a = new ActiveXObject('MSXML2.XMLHTTP');
  509. return a;
  510. } catch(e){}
  511. try {
  512. var b = new ActiveXObject('Microsoft.XMLHTTP');
  513. return b;
  514. } catch(e){}
  515. }
  516. return false;
  517. },
  518. /**
  519. * This is the base for XHR based transports, the `XHR-Polling` and the `XHR-multipart`
  520. * transports will extend this class.
  521. *
  522. * @constructor
  523. * @extends {io.Transport}
  524. * @property {Array} sendBuffer Used to queue up messages so they can be send as one request.
  525. * @api public
  526. */
  527. XHR = io.Transport.XHR = function(){
  528. io.Transport.apply(this, arguments);
  529. this.sendBuffer = [];
  530. };
  531. io.util.inherit(XHR, io.Transport);
  532. /**
  533. * Establish a connection
  534. *
  535. * @returns {Transport}
  536. * @api public
  537. */
  538. XHR.prototype.connect = function(){
  539. this.get();
  540. return this;
  541. };
  542. /**
  543. * Check if we need to send data to the Socket.IO server, if we have data in our buffer
  544. * we encode it and forward it to the sendIORequest method.
  545. *
  546. * @api private
  547. */
  548. XHR.prototype.checkSend = function(){
  549. if (!this.posting && this.sendBuffer.length){
  550. var encoded = this.encode(this.sendBuffer);
  551. this.sendBuffer = [];
  552. this.sendIORequest(encoded);
  553. }
  554. };
  555. /**
  556. * Send data to the Socket.IO server.
  557. *
  558. * @param data The message
  559. * @returns {Transport}
  560. * @api public
  561. */
  562. XHR.prototype.send = function(data){
  563. if (io.util.isArray(data)){
  564. this.sendBuffer.push.apply(this.sendBuffer, data);
  565. } else {
  566. this.sendBuffer.push(data);
  567. }
  568. this.checkSend();
  569. return this;
  570. };
  571. /**
  572. * Posts a encoded message to the Socket.IO server.
  573. *
  574. * @param {String} data A encoded message.
  575. * @api private
  576. */
  577. XHR.prototype.sendIORequest = function(data){
  578. var self = this;
  579. this.posting = true;
  580. this.sendXHR = this.request('send', 'POST');
  581. this.sendXHR.onreadystatechange = function(){
  582. var status;
  583. if (self.sendXHR.readyState == 4){
  584. self.sendXHR.onreadystatechange = empty;
  585. try { status = self.sendXHR.status; } catch(e){}
  586. self.posting = false;
  587. if (status == 200){
  588. self.checkSend();
  589. } else {
  590. self.onDisconnect();
  591. }
  592. }
  593. };
  594. this.sendXHR.send('data=' + encodeURIComponent(data));
  595. };
  596. /**
  597. * Disconnect the established connection.
  598. *
  599. * @returns {Transport}.
  600. * @api public
  601. */
  602. XHR.prototype.disconnect = function(){
  603. // send disconnection signal
  604. this.onDisconnect();
  605. return this;
  606. };
  607. /**
  608. * Handle the disconnect request.
  609. *
  610. * @api private
  611. */
  612. XHR.prototype.onDisconnect = function(){
  613. if (this.xhr){
  614. this.xhr.onreadystatechange = empty;
  615. try {
  616. this.xhr.abort();
  617. } catch(e){}
  618. this.xhr = null;
  619. }
  620. if (this.sendXHR){
  621. this.sendXHR.onreadystatechange = empty;
  622. try {
  623. this.sendXHR.abort();
  624. } catch(e){}
  625. this.sendXHR = null;
  626. }
  627. this.sendBuffer = [];
  628. io.Transport.prototype.onDisconnect.call(this);
  629. };
  630. /**
  631. * Generates a configured XHR request
  632. *
  633. * @param {String} url The url that needs to be requested.
  634. * @param {String} method The method the request should use.
  635. * @param {Boolean} multipart Do a multipart XHR request
  636. * @returns {XMLHttpRequest}
  637. * @api private
  638. */
  639. XHR.prototype.request = function(url, method, multipart){
  640. var req = request(this.base.isXDomain());
  641. if (multipart) req.multipart = true;
  642. req.open(method || 'GET', this.prepareUrl() + (url ? '/' + url : ''));
  643. if (method == 'POST' && 'setRequestHeader' in req){
  644. req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
  645. }
  646. return req;
  647. };
  648. /**
  649. * Check if the XHR transports are supported
  650. *
  651. * @param {Boolean} xdomain Check if we support cross domain requests.
  652. * @returns {Boolean}
  653. * @api public
  654. */
  655. XHR.check = function(xdomain){
  656. try {
  657. if (request(xdomain)) return true;
  658. } catch(e){}
  659. return false;
  660. };
  661. /**
  662. * Check if the XHR transport supports corss domain requests.
  663. *
  664. * @returns {Boolean}
  665. * @api public
  666. */
  667. XHR.xdomainCheck = function(){
  668. return XHR.check(true);
  669. };
  670. XHR.request = request;
  671. })();
  672. /**
  673. * socket.io-node-client
  674. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  675. * MIT Licensed
  676. */
  677. (function(){
  678. var io = this.io,
  679. /**
  680. * The WebSocket transport uses the HTML5 WebSocket API to establish an persistent
  681. * connection with the Socket.IO server. This transport will also be inherited by the
  682. * FlashSocket fallback as it provides a API compatible polyfill for the WebSockets.
  683. *
  684. * @constructor
  685. * @extends {io.Transport}
  686. * @api public
  687. */
  688. WS = io.Transport.websocket = function(){
  689. io.Transport.apply(this, arguments);
  690. };
  691. io.util.inherit(WS, io.Transport);
  692. /**
  693. * The transport type, you use this to identify which transport was chosen.
  694. *
  695. * @type {String}
  696. * @api public
  697. */
  698. WS.prototype.type = 'websocket';
  699. /**
  700. * Initializes a new `WebSocket` connection with the Socket.IO server. We attach
  701. * all the appropriate listeners to handle the responses from the server.
  702. *
  703. * @returns {Transport}
  704. * @api public
  705. */
  706. WS.prototype.connect = function(){
  707. var self = this;
  708. this.socket = new WebSocket(this.prepareUrl());
  709. this.socket.onmessage = function(ev){ self.onData(ev.data); };
  710. this.socket.onclose = function(ev){ self.onDisconnect(); };
  711. this.socket.onerror = function(e){ self.onError(e); };
  712. return this;
  713. };
  714. /**
  715. * Send a message to the Socket.IO server. The message will automatically be encoded
  716. * in the correct message format.
  717. *
  718. * @returns {Transport}
  719. * @api public
  720. */
  721. WS.prototype.send = function(data){
  722. if (this.socket) this.socket.send(this.encode(data));
  723. return this;
  724. };
  725. /**
  726. * Disconnect the established `WebSocket` connection.
  727. *
  728. * @returns {Transport}
  729. * @api public
  730. */
  731. WS.prototype.disconnect = function(){
  732. if (this.socket) this.socket.close();
  733. return this;
  734. };
  735. /**
  736. * Handle the errors that `WebSocket` might be giving when we
  737. * are attempting to connect or send messages.
  738. *
  739. * @param {Error} e The error.
  740. * @api private
  741. */
  742. WS.prototype.onError = function(e){
  743. this.base.emit('error', [e]);
  744. };
  745. /**
  746. * Generate a `WebSocket` compatible URL based on the options
  747. * the user supplied in our Socket.IO base.
  748. *
  749. * @returns {String} Connection url
  750. * @api private
  751. */
  752. WS.prototype.prepareUrl = function(){
  753. return (this.base.options.secure ? 'wss' : 'ws')
  754. + '://' + this.base.host
  755. + ':' + this.base.options.port
  756. + '/' + this.base.options.resource
  757. + '/' + this.type
  758. + (this.sessionid ? ('/' + this.sessionid) : '');
  759. };
  760. /**
  761. * Checks if the browser has support for native `WebSockets` and that
  762. * it's not the polyfill created for the FlashSocket transport.
  763. *
  764. * @return {Boolean}
  765. * @api public
  766. */
  767. WS.check = function(){
  768. // we make sure WebSocket is not confounded with a previously loaded flash WebSocket
  769. return 'WebSocket' in window && WebSocket.prototype && ( WebSocket.prototype.send && !!WebSocket.prototype.send.toString().match(/native/i)) && typeof WebSocket !== "undefined";
  770. };
  771. /**
  772. * Check if the `WebSocket` transport support cross domain communications.
  773. *
  774. * @returns {Boolean}
  775. * @api public
  776. */
  777. WS.xdomainCheck = function(){
  778. return true;
  779. };
  780. })();
  781. /**
  782. * socket.io-node-client
  783. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  784. * MIT Licensed
  785. */
  786. (function(){
  787. var io = this.io,
  788. /**
  789. * The Flashsocket transport. This is a API wrapper for the HTML5 WebSocket specification.
  790. * It uses a .swf file to communicate with the server. If you want to serve the .swf file
  791. * from a other server than where the Socket.IO script is coming from you need to use the
  792. * insecure version of the .swf. More information about this can be found on the github page.
  793. *
  794. * @constructor
  795. * @extends {io.Transport.websocket}
  796. * @api public
  797. */
  798. Flashsocket = io.Transport.flashsocket = function(){
  799. io.Transport.websocket.apply(this, arguments);
  800. };
  801. io.util.inherit(Flashsocket, io.Transport.websocket);
  802. /**
  803. * The transport type, you use this to identify which transport was chosen.
  804. *
  805. * @type {String}
  806. * @api public
  807. */
  808. Flashsocket.prototype.type = 'flashsocket';
  809. /**
  810. * Disconnect the established `Flashsocket` connection. This is done by adding a new
  811. * task to the Flashsocket. The rest will be handled off by the `WebSocket` transport.
  812. *
  813. * @returns {Transport}
  814. * @api public
  815. */
  816. Flashsocket.prototype.connect = function(){
  817. var self = this, args = arguments;
  818. WebSocket.__addTask(function(){
  819. io.Transport.websocket.prototype.connect.apply(self, args);
  820. });
  821. return this;
  822. };
  823. /**
  824. * Sends a message to the Socket.IO server. This is done by adding a new
  825. * task to the Flashsocket. The rest will be handled off by the `WebSocket` transport.
  826. *
  827. * @returns {Transport}
  828. * @api public
  829. */
  830. Flashsocket.prototype.send = function(){
  831. var self = this, args = arguments;
  832. WebSocket.__addTask(function(){
  833. io.Transport.websocket.prototype.send.apply(self, args);
  834. });
  835. return this;
  836. };
  837. /**
  838. * Check if the Flashsocket transport is supported as it requires that the Adobe Flash Player
  839. * plugin version `10.0.0` or greater is installed. And also check if the polyfill is correctly
  840. * loaded.
  841. *
  842. * @returns {Boolean}
  843. * @api public
  844. */
  845. Flashsocket.check = function(){
  846. if (typeof WebSocket == 'undefined' || !('__addTask' in WebSocket) || !swfobject) return false;
  847. return swfobject.hasFlashPlayerVersion("10.0.0");
  848. };
  849. /**
  850. * Check if the Flashsocket transport can be used as cross domain / cross origin transport.
  851. * Because we can't see which type (secure or insecure) of .swf is used we will just return true.
  852. *
  853. * @returns {Boolean}
  854. * @api public
  855. */
  856. Flashsocket.xdomainCheck = function(){
  857. return true;
  858. };
  859. })();
  860. /**
  861. * socket.io-node-client
  862. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  863. * MIT Licensed
  864. */
  865. (function(){
  866. var io = this.io,
  867. /**
  868. * The HTMLFile transport creates a `forever iframe` based transport
  869. * for Internet Explorer. Regular forever iframe implementations will
  870. * continuously trigger the browsers buzy indicators. If the forever iframe
  871. * is created inside a `htmlfile` these indicators will not be trigged.
  872. *
  873. * @constructor
  874. * @extends {io.Transport.XHR}
  875. * @api public
  876. */
  877. HTMLFile = io.Transport.htmlfile = function(){
  878. io.Transport.XHR.apply(this, arguments);
  879. };
  880. io.util.inherit(HTMLFile, io.Transport.XHR);
  881. /**
  882. * The transport type, you use this to identify which transport was chosen.
  883. *
  884. * @type {String}
  885. * @api public
  886. */
  887. HTMLFile.prototype.type = 'htmlfile';
  888. /**
  889. * Starts the HTMLFile data stream for incoming messages. And registers a
  890. * onunload event listener so the HTMLFile will be destroyed.
  891. *
  892. * @api private
  893. */
  894. HTMLFile.prototype.get = function(){
  895. var self = this;
  896. this.open();
  897. window.attachEvent('onunload', function(){ self.destroy(); });
  898. };
  899. /**
  900. * Creates a new ActiveX `htmlfile` with a forever loading iframe
  901. * that can be used to listen to messages. Inside the generated
  902. * `htmlfile` a reference will be made to the HTMLFile transport.
  903. *
  904. * @api private
  905. */
  906. HTMLFile.prototype.open = function(){
  907. this.doc = new ActiveXObject('htmlfile');
  908. this.doc.open();
  909. this.doc.write('<html></html>');
  910. this.doc.parentWindow.s = this;
  911. this.doc.close();
  912. var iframeC = this.doc.createElement('div');
  913. this.doc.body.appendChild(iframeC);
  914. this.iframe = this.doc.createElement('iframe');
  915. iframeC.appendChild(this.iframe);
  916. this.iframe.src = this.prepareUrl() + '/' + (+ new Date);
  917. };
  918. /**
  919. * The Socket.IO server will write script tags inside the forever
  920. * iframe, this function will be used as callback for the incoming
  921. * information.
  922. *
  923. * @param {String} data The message
  924. * @param {document} doc Reference to the context
  925. * @api private
  926. */
  927. HTMLFile.prototype._ = function(data, doc){
  928. this.onData(data);
  929. var script = doc.getElementsByTagName('script')[0];
  930. script.parentNode.removeChild(script);
  931. };
  932. /**
  933. * Destroy the established connection, iframe and `htmlfile`.
  934. * And calls the `CollectGarbage` function of Internet Explorer
  935. * to release the memory.
  936. *
  937. * @api private
  938. */
  939. HTMLFile.prototype.destroy = function(){
  940. if (this.iframe){
  941. try {
  942. this.iframe.src = 'about:blank';
  943. } catch(e){}
  944. this.doc = null;
  945. CollectGarbage();
  946. }
  947. };
  948. /**
  949. * Disconnects the established connection.
  950. *
  951. * @returns {Transport} Chaining.
  952. * @api public
  953. */
  954. HTMLFile.prototype.disconnect = function(){
  955. this.destroy();
  956. return io.Transport.XHR.prototype.disconnect.call(this);
  957. };
  958. /**
  959. * Checks if the browser supports this transport. The browser
  960. * must have an `ActiveXObject` implementation.
  961. *
  962. * @return {Boolean}
  963. * @api public
  964. */
  965. HTMLFile.check = function(){
  966. if ('ActiveXObject' in window){
  967. try {
  968. var a = new ActiveXObject('htmlfile');
  969. return a && io.Transport.XHR.check();
  970. } catch(e){}
  971. }
  972. return false;
  973. };
  974. /**
  975. * Check if cross domain requests are supported.
  976. *
  977. * @returns {Boolean}
  978. * @api public
  979. */
  980. HTMLFile.xdomainCheck = function(){
  981. // we can probably do handling for sub-domains, we should test that it's cross domain but a subdomain here
  982. return false;
  983. };
  984. })();
  985. /**
  986. * socket.io-node-client
  987. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  988. * MIT Licensed
  989. */
  990. (function(){
  991. var io = this.io,
  992. /**
  993. * The XHR-Multipart transport uses the a multipart XHR connection to
  994. * stream in the data from the Socket.IO server
  995. *
  996. * @constructor
  997. * @extends {io.Transport.XHR}
  998. * @api public
  999. */
  1000. XHRMultipart = io.Transport['xhr-multipart'] = function(){
  1001. io.Transport.XHR.apply(this, arguments);
  1002. };
  1003. io.util.inherit(XHRMultipart, io.Transport.XHR);
  1004. /**
  1005. * The transport type, you use this to identify which transport was chosen.
  1006. *
  1007. * @type {String}
  1008. * @api public
  1009. */
  1010. XHRMultipart.prototype.type = 'xhr-multipart';
  1011. /**
  1012. * Starts the multipart stream for incomming messages.
  1013. *
  1014. * @api private
  1015. */
  1016. XHRMultipart.prototype.get = function(){
  1017. var self = this;
  1018. this.xhr = this.request('', 'GET', true);
  1019. this.xhr.onreadystatechange = function(){
  1020. if (self.xhr.readyState == 4) self.onData(self.xhr.responseText);
  1021. };
  1022. this.xhr.send(null);
  1023. };
  1024. /**
  1025. * Checks if browser supports this transport.
  1026. *
  1027. * @return {Boolean}
  1028. * @api public
  1029. */
  1030. XHRMultipart.check = function(){
  1031. return 'XMLHttpRequest' in window && 'prototype' in XMLHttpRequest && 'multipart' in XMLHttpRequest.prototype;
  1032. };
  1033. /**
  1034. * Check if cross domain requests are supported.
  1035. *
  1036. * @returns {Boolean}
  1037. * @api public
  1038. */
  1039. XHRMultipart.xdomainCheck = function(){
  1040. return true;
  1041. };
  1042. })();
  1043. /**
  1044. * socket.io-node-client
  1045. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1046. * MIT Licensed
  1047. */
  1048. (function(){
  1049. var io = this.io,
  1050. /**
  1051. * A small stub function that will be used to reduce memory leaks.
  1052. *
  1053. * @type {Function}
  1054. * @api private
  1055. */
  1056. empty = new Function(),
  1057. /**
  1058. * The XHR-polling transport uses long polling XHR requests to create a
  1059. * "persistent" connection with the server.
  1060. *
  1061. * @constructor
  1062. * @extends {io.Transport.XHR}
  1063. * @api public
  1064. */
  1065. XHRPolling = io.Transport['xhr-polling'] = function(){
  1066. io.Transport.XHR.apply(this, arguments);
  1067. };
  1068. io.util.inherit(XHRPolling, io.Transport.XHR);
  1069. /**
  1070. * The transport type, you use this to identify which transport was chosen.
  1071. *
  1072. * @type {string}
  1073. * @api public
  1074. */
  1075. XHRPolling.prototype.type = 'xhr-polling';
  1076. /**
  1077. * Establish a connection, for iPhone and Android this will be done once the page
  1078. * is loaded.
  1079. *
  1080. * @returns {Transport} Chaining.
  1081. * @api public
  1082. */
  1083. XHRPolling.prototype.connect = function(){
  1084. var self = this;
  1085. io.util.defer(function(){ io.Transport.XHR.prototype.connect.call(self) });
  1086. return false;
  1087. };
  1088. /**
  1089. * Starts a XHR request to wait for incoming messages.
  1090. *
  1091. * @api private
  1092. */
  1093. XHRPolling.prototype.get = function(){
  1094. var self = this;
  1095. this.xhr = this.request(+ new Date, 'GET');
  1096. this.xhr.onreadystatechange = function(){
  1097. var status;
  1098. if (self.xhr.readyState == 4){
  1099. self.xhr.onreadystatechange = empty;
  1100. try { status = self.xhr.status; } catch(e){}
  1101. if (status == 200){
  1102. self.onData(self.xhr.responseText);
  1103. self.get();
  1104. } else {
  1105. self.onDisconnect();
  1106. }
  1107. }
  1108. };
  1109. this.xhr.send(null);
  1110. };
  1111. /**
  1112. * Checks if browser supports this transport.
  1113. *
  1114. * @return {Boolean}
  1115. * @api public
  1116. */
  1117. XHRPolling.check = function(){
  1118. return io.Transport.XHR.check();
  1119. };
  1120. /**
  1121. * Check if cross domain requests are supported
  1122. *
  1123. * @returns {Boolean}
  1124. * @api public
  1125. */
  1126. XHRPolling.xdomainCheck = function(){
  1127. return io.Transport.XHR.xdomainCheck();
  1128. };
  1129. })();
  1130. /**
  1131. * socket.io-node-client
  1132. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1133. * MIT Licensed
  1134. */
  1135. (function(){
  1136. var io = this.io,
  1137. /**
  1138. * The JSONP transport creates an persistent connection by dynamically
  1139. * inserting a script tag in the page. This script tag will receive the
  1140. * information of the Socket.IO server. When new information is received
  1141. * it creates a new script tag for the new data stream.
  1142. *
  1143. * @constructor
  1144. * @extends {io.Transport.xhr-polling}
  1145. * @api public
  1146. */
  1147. JSONPPolling = io.Transport['jsonp-polling'] = function(){
  1148. io.Transport.XHR.apply(this, arguments);
  1149. this.insertAt = document.getElementsByTagName('head')[0];
  1150. this.index = io.JSONP.length;
  1151. io.JSONP.push(this);
  1152. };
  1153. io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
  1154. /**
  1155. * A list of all JSONPolling transports, this is used for by
  1156. * the Socket.IO server to distribute the callbacks.
  1157. *
  1158. * @type {Array}
  1159. * @api private
  1160. */
  1161. io.JSONP = [];
  1162. /**
  1163. * The transport type, you use this to identify which transport was chosen.
  1164. *
  1165. * @type {String}
  1166. * @api public
  1167. */
  1168. JSONPPolling.prototype.type = 'jsonp-polling';
  1169. /**
  1170. * Posts a encoded message to the Socket.IO server using an iframe.
  1171. * The iframe is used because script tags can create POST based requests.
  1172. * The iframe is positioned outside of the view so the user does not
  1173. * notice it's existence.
  1174. *
  1175. * @param {String} data A encoded message.
  1176. * @api private
  1177. */
  1178. JSONPPolling.prototype.sendIORequest = function(data){
  1179. var self = this;
  1180. if (!('form' in this)){
  1181. var form = document.createElement('FORM'),
  1182. area = document.createElement('TEXTAREA'),
  1183. id = this.iframeId = 'socket_io_iframe_' + this.index,
  1184. iframe;
  1185. form.style.position = 'absolute';
  1186. form.style.top = '-1000px';
  1187. form.style.left = '-1000px';
  1188. form.target = id;
  1189. form.method = 'POST';
  1190. form.action = this.prepareUrl() + '/' + (+new Date) + '/' + this.index;
  1191. area.name = 'data';
  1192. form.appendChild(area);
  1193. this.insertAt.insertBefore(form, null);
  1194. document.body.appendChild(form);
  1195. this.form = form;
  1196. this.area = area;
  1197. }
  1198. function complete(){
  1199. initIframe();
  1200. self.posting = false;
  1201. self.checkSend();
  1202. };
  1203. function initIframe(){
  1204. if (self.iframe){
  1205. self.form.removeChild(self.iframe);
  1206. }
  1207. try {
  1208. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  1209. iframe = document.createElement('<iframe name="'+ self.iframeId +'">');
  1210. } catch(e){
  1211. iframe = document.createElement('iframe');
  1212. iframe.name = self.iframeId;
  1213. }
  1214. iframe.id = self.iframeId;
  1215. self.form.appendChild(iframe);
  1216. self.iframe = iframe;
  1217. };
  1218. initIframe();
  1219. this.posting = true;
  1220. this.area.value = data;
  1221. try {
  1222. this.form.submit();
  1223. } catch(e){}
  1224. if (this.iframe.attachEvent){
  1225. iframe.onreadystatechange = function(){
  1226. if (self.iframe.readyState == 'complete') complete();
  1227. };
  1228. } else {
  1229. this.iframe.onload = complete;
  1230. }
  1231. };
  1232. /**
  1233. * Creates a new JSONP poll that can be used to listen
  1234. * for messages from the Socket.IO server.
  1235. *
  1236. * @api private
  1237. */
  1238. JSONPPolling.prototype.get = function(){
  1239. var self = this,
  1240. script = document.createElement('SCRIPT');
  1241. if (this.script){
  1242. this.script.parentNode.removeChild(this.script);
  1243. this.script = null;
  1244. }
  1245. script.async = true;
  1246. script.src = this.prepareUrl() + '/' + (+new Date) + '/' + this.index;
  1247. script.onerror = function(){
  1248. self.onDisconnect();
  1249. };
  1250. this.insertAt.insertBefore(script, null);
  1251. this.script = script;
  1252. };
  1253. /**
  1254. * Callback function for the incoming message stream from the Socket.IO server.
  1255. *
  1256. * @param {String} data The message
  1257. * @param {document} doc Reference to the context
  1258. * @api private
  1259. */
  1260. JSONPPolling.prototype._ = function(){
  1261. this.onData.apply(this, arguments);
  1262. this.get();
  1263. return this;
  1264. };
  1265. /**
  1266. * Checks if browser supports this transport.
  1267. *
  1268. * @return {Boolean}
  1269. * @api public
  1270. */
  1271. JSONPPolling.check = function(){
  1272. return true;
  1273. };
  1274. /**
  1275. * Check if cross domain requests are supported
  1276. *
  1277. * @returns {Boolean}
  1278. * @api public
  1279. */
  1280. JSONPPolling.xdomainCheck = function(){
  1281. return true;
  1282. };
  1283. })();
  1284. /**
  1285. * socket.io-node-client
  1286. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1287. * MIT Licensed
  1288. */
  1289. (function(){
  1290. var io = this.io;
  1291. /**
  1292. * Create a new `Socket.IO client` which can establish a persisted
  1293. * connection with a Socket.IO enabled server.
  1294. *
  1295. * Options:
  1296. * - `secure` Use secure connections, defaulting to false.
  1297. * - `document` Reference to the document object to retrieve and set cookies, defaulting to document.
  1298. * - `port` The port where the Socket.IO server listening on, defaulting to location.port.
  1299. * - `resource` The path or namespace on the server where the Socket.IO requests are intercepted, defaulting to 'socket.io'.
  1300. * - `transports` A ordered list with the available transports, defaulting to all transports.
  1301. * - `transportOption` A {Object} containing the options for each transport. The key of the object should reflect
  1302. * name of the transport and the value a {Object} with the options.
  1303. * - `connectTimeout` The duration in milliseconds that a transport has to establish a working connection, defaulting to 5000.
  1304. * - `tryTransportsOnConnectTimeout` Should we attempt other transport methods when the connectTimeout occurs, defaulting to true.
  1305. * - `reconnect` Should reconnection happen automatically, defaulting to true.
  1306. * - `reconnectionDelay` The delay in milliseconds before we attempt to establish a working connection. This value will
  1307. * increase automatically using a exponential back off algorithm. Defaulting to 500.
  1308. * - `maxReconnectionAttempts` Number of attempts we should make before seizing the reconnect operation, defaulting to 10.
  1309. * - `rememberTransport` Should the successfully connected transport be remembered in a cookie, defaulting to true.
  1310. *
  1311. * Examples:
  1312. *
  1313. * Create client with the default settings.
  1314. *
  1315. * var socket = new io.Socket();
  1316. * socket.connect();
  1317. * socket.on('message', function(msg){
  1318. * console.log('Received message: ' + msg );
  1319. * });
  1320. * socket.on('connect', function(){
  1321. * socket.send('Hello from client');
  1322. * });
  1323. *
  1324. * Create a connection with server on a different port and host.
  1325. *
  1326. * var socket = new io.Socket('http://example.com',{port:1337});
  1327. *
  1328. * @constructor
  1329. * @exports Socket as io.Socket
  1330. * @param {String} [host] The host where the Socket.IO server is located, it defaults to the host that runs the page.
  1331. * @param {Objects} [options] The options that will configure the Socket.IO client.
  1332. * @property {String} host The supplied host arguments or the host that page runs.
  1333. * @property {Object} options The passed options combined with the defaults.
  1334. * @property {Boolean} connected Whether the socket is connected or not.
  1335. * @property {Boolean} connecting Whether the socket is connecting or not.
  1336. * @property {Boolean} reconnecting Whether the socket is reconnecting or not.
  1337. * @property {Object} transport The selected transport instance.
  1338. * @api public
  1339. */
  1340. var Socket = io.Socket = function(host, options){
  1341. this.host = host || document.domain;
  1342. this.options = {
  1343. secure: false,
  1344. document: document,
  1345. port: document.location.port || 80,
  1346. resource: 'socket.io',
  1347. transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
  1348. transportOptions: {
  1349. 'xhr-polling': {
  1350. timeout: 25000 // based on polling duration default
  1351. },
  1352. 'jsonp-polling': {
  1353. timeout: 25000
  1354. }
  1355. },
  1356. connectTimeout: 5000,
  1357. tryTransportsOnConnectTimeout: true,
  1358. reconnect: true,
  1359. reconnectionDelay: 500,
  1360. maxReconnectionAttempts: 10,
  1361. rememberTransport: true
  1362. };
  1363. io.util.merge(this.options, options);
  1364. this.connected = false;
  1365. this.connecting = false;
  1366. this.reconnecting = false;
  1367. this.events = {};
  1368. this.transport = this.getTransport();
  1369. if (!this.transport && 'console' in window) console.error('No transport available');
  1370. };
  1371. /**
  1372. * Find an available transport based on the options supplied in the constructor. For example if the
  1373. * `rememberTransport` option was set we will only connect with the previous successfully connected transport.
  1374. * The supplied transports can be overruled if the `override` argument is supplied.
  1375. *
  1376. * Example:
  1377. *
  1378. * Override the existing transports.
  1379. *
  1380. * var socket = new io.Socket();
  1381. * socket.getTransport(['jsonp-polling','websocket']);
  1382. * // returns the json-polling transport because it's availabe in all browsers.
  1383. *
  1384. * @param {Array} [override] A ordered list with transports that should be used instead of the options.transports.
  1385. * @returns {Null|Transport} The available transport.
  1386. * @api private
  1387. */
  1388. Socket.prototype.getTransport = function(override){
  1389. var transports = override || this.options.transports, match;
  1390. if (this.options.rememberTransport && !override){
  1391. match = this.options.document.cookie.match('(?:^|;)\\s*socketio=([^;]*)');
  1392. if (match){
  1393. this.rememberedTransport = true;
  1394. transports = [decodeURIComponent(match[1])];
  1395. }
  1396. }
  1397. for (var i = 0, transport; transport = transports[i]; i++){
  1398. if (io.Transport[transport]
  1399. && io.Transport[transport].check()
  1400. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())){
  1401. return new io.Transport[transport](this, this.options.transportOptions[transport] || {});
  1402. }
  1403. }
  1404. return null;
  1405. };
  1406. /**
  1407. * Establish a new connection with the Socket.IO server. This is done using the selected transport by the
  1408. * getTransport method. If the `connectTimeout` and the `tryTransportsOnConnectTimeout` options are set
  1409. * the client will keep trying to connect to the server using a different transports when the timeout occurs.
  1410. *
  1411. * Example:
  1412. *
  1413. * Create a Socket.IO client with a connect callback (We assume we have the WebSocket transport avaliable).
  1414. *
  1415. * var socket = new io.Socket();
  1416. * socket.connect(function(transport){
  1417. * console.log("Connected to server using the " + socket.transport.type + " transport.");
  1418. * });
  1419. * // => "Connected to server using the WebSocket transport."
  1420. *
  1421. * @param {Function} [fn] Callback.
  1422. * @returns {io.Socket}
  1423. * @api public
  1424. */
  1425. Socket.prototype.connect = function(fn){
  1426. if (this.transport && !this.connected){
  1427. if (this.connecting) this.disconnect(true);
  1428. this.connecting = true;
  1429. this.emit('connecting', [this.transport.type]);
  1430. this.transport.connect();
  1431. if (this.options.connectTimeout){
  1432. var self = this;
  1433. this.connectTimeoutTimer = setTimeout(function(){
  1434. if (!self.connected){
  1435. self.disconnect(true);
  1436. if (self.options.tryTransportsOnConnectTimeout && !self.rememberedTransport){
  1437. if(!self.remainingTransports) self.remainingTransports = self.options.transports.slice(0);
  1438. var transports = self.remainingTransports;
  1439. while(transports.length > 0 && transports.splice(0,1)[0] != self.transport.type){}
  1440. if(transports.length){
  1441. self.transport = self.getTransport(transports);
  1442. self.connect();
  1443. }
  1444. }
  1445. if(!self.remainingTransports || self.remainingTransports.length == 0) self.emit('connect_failed');
  1446. }
  1447. if(self.remainingTransports && self.remainingTransports.length == 0) delete self.remainingTransports;
  1448. }, this.options.connectTimeout);
  1449. }
  1450. }
  1451. if (fn && typeof fn == 'function') this.once('connect',fn);
  1452. return this;
  1453. };
  1454. /**
  1455. * Sends the data to the Socket.IO server. If there isn't a connection to the server
  1456. * the data will be forwarded to the queue.
  1457. *
  1458. * @param {Mixed} data The data that needs to be send to the Socket.IO server.
  1459. * @returns {io.Socket}
  1460. * @api public
  1461. */
  1462. Socket.prototype.send = function(data){
  1463. if (!this.transport || !this.transport.connected) return this.queue(data);
  1464. this.transport.send(data);
  1465. return this;
  1466. };
  1467. /**
  1468. * Disconnect the established connect.
  1469. *
  1470. * @param {Boolean} [soft] A soft disconnect will keep the reconnect settings enabled.
  1471. * @returns {io.Socket}
  1472. * @api public
  1473. */
  1474. Socket.prototype.disconnect = function(soft){
  1475. if (this.connectTimeoutTimer) clearTimeout(this.connectTimeoutTimer);
  1476. if (!soft) this.options.reconnect = false;
  1477. this.transport.disconnect();
  1478. return this;
  1479. };
  1480. /**
  1481. * Adds a new eventListener for the given event.
  1482. *
  1483. * Example:
  1484. *
  1485. * var socket = new io.Socket();
  1486. * socket.on("connect", function(transport){
  1487. * console.log("Connected to server using the " + socket.transport.type + " transport.");
  1488. * });
  1489. * // => "Connected to server using the WebSocket transport."
  1490. *
  1491. * @param {String} name The name of the event.
  1492. * @param {Function} fn The function that is called once the event is emitted.
  1493. * @returns {io.Socket}
  1494. * @api public
  1495. */
  1496. Socket.prototype.on = function(name, fn){
  1497. if (!(name in this.events)) this.events[name] = [];
  1498. this.events[name].push(fn);
  1499. return this;
  1500. };
  1501. /**
  1502. * Adds a one time listener, the listener will be removed after the event is emitted.
  1503. *
  1504. * Example:
  1505. *
  1506. * var socket = new io.Socket();
  1507. * socket.once("custom:event", function(){
  1508. * console.log("I should only log once.");
  1509. * });
  1510. * socket.emit("custom:event");
  1511. * socket.emit("custom:event");
  1512. * // => "I should only log once."
  1513. *
  1514. * @param {String} name The name of the event.
  1515. * @param {Function} fn The function that is called once the event is emitted.
  1516. * @returns {io.Socket}
  1517. * @api public
  1518. */
  1519. Socket.prototype.once = function(name, fn){
  1520. var self = this
  1521. , once = function(){
  1522. self.removeEvent(name, once);
  1523. fn.apply(self, arguments);
  1524. };
  1525. once.ref = fn;
  1526. self.on(name, once);
  1527. return this;
  1528. };
  1529. /**
  1530. * Emit a event to all listeners.
  1531. *
  1532. * Example:
  1533. *
  1534. * var socket = new io.Socket();
  1535. * socket.on("custom:event", function(){
  1536. * console.log("Emitted a custom:event");
  1537. * });
  1538. * socket.emit("custom:event");
  1539. * // => "Emitted a custom:event"
  1540. *
  1541. * @param {String} name The name of the event.
  1542. * @param {Array} args Arguments for the event.
  1543. * @returns {io.Socket}
  1544. * @api private
  1545. */
  1546. Socket.prototype.emit = function(name, args){
  1547. if (name in this.events){
  1548. var events = this.events[name].concat();
  1549. for (var i = 0, ii = events.length; i < ii; i++)
  1550. events[i].apply(this, args === undefined ? [] : args);
  1551. }
  1552. return this;
  1553. };
  1554. /**
  1555. * Removes a event listener from the listener array for the specified event.
  1556. *
  1557. * Example:
  1558. *
  1559. * var socket = new io.Socket()
  1560. * , event = function(){};
  1561. * socket.on("connect", event);
  1562. * socket.removeEvent("connect", event);
  1563. *
  1564. * @param {String} name The name of the event.
  1565. * @param {Function} fn The function that is called once the event is emitted.
  1566. * @returns {io.Socket}
  1567. * @api public
  1568. */
  1569. Socket.prototype.removeEvent = function(name, fn){
  1570. if (name in this.events){
  1571. for (var a = 0, l = this.events[name].length; a < l; a++)
  1572. if (this.events[name][a] == fn || this.events[name][a].ref && this.events[name][a].ref == fn) this.events[name].splice(a, 1);
  1573. }
  1574. return this;
  1575. };
  1576. /**
  1577. * Queues messages when there isn't a active connection available. Once a connection has been
  1578. * established you should call the `doQueue` method to send the queued messages to the server.
  1579. *
  1580. * @param {Mixed} message The message that was originally send to the `send` method.
  1581. * @returns {io.Socket}
  1582. * @api private
  1583. */
  1584. Socket.prototype.queue = function(message){
  1585. if (!('queueStack' in this)) this.queueStack = [];
  1586. this.queueStack.push(message);
  1587. return this;
  1588. };
  1589. /**
  1590. * If there are queued messages we send all messages to the Socket.IO server and empty
  1591. * the queue.
  1592. *
  1593. * @returns {io.Socket}
  1594. * @api private
  1595. */
  1596. Socket.prototype.doQueue = function(){
  1597. if (!('queueStack' in this) || !this.queueStack.length) return this;
  1598. this.transport.send(this.queueStack);
  1599. this.queueStack = [];
  1600. return this;
  1601. };
  1602. /**
  1603. * Check if we need to use cross domain enabled transports. Cross domain would
  1604. * be a different port or different domain name.
  1605. *
  1606. * @returns {Boolean}
  1607. * @api private
  1608. */
  1609. Socket.prototype.isXDomain = function(){
  1610. var locPort = window.location.port || 80;
  1611. return this.host !== document.domain || this.options.port != locPort;
  1612. };
  1613. /**
  1614. * When the transport established an working connection the Socket.IO server it notifies us
  1615. * by calling this method so we can set the `connected` and `connecting` properties and emit
  1616. * the connection event.
  1617. *
  1618. * @api private
  1619. */
  1620. Socket.prototype.onConnect = function(){
  1621. this.connected = true;
  1622. this.connecting = false;
  1623. this.doQueue();
  1624. if (this.options.rememberTransport) this.options.document.cookie = 'socketio=' + encodeURIComponent(this.transport.type);
  1625. this.emit('connect');
  1626. };
  1627. /**
  1628. * When the transport receives new messages from the Socket.IO server it notifies us by calling
  1629. * this method with the decoded `data` it received.
  1630. *
  1631. * @param data The message from the Socket.IO server.
  1632. * @api private
  1633. */
  1634. Socket.prototype.onMessage = function(data){
  1635. this.emit('message', [data]);
  1636. };
  1637. /**
  1638. * When the transport is disconnected from the Socket.IO server it notifies us by calling
  1639. * this method. If we where connected and the `reconnect` is set we will attempt to reconnect.
  1640. *
  1641. * @api private
  1642. */
  1643. Socket.prototype.onDisconnect = function(){
  1644. var wasConnected = this.connected;
  1645. this.connected = false;
  1646. this.connecting = false;
  1647. this.queueStack = [];
  1648. if (wasConnected){
  1649. this.emit('disconnect');
  1650. if (this.options.reconnect && !this.reconnecting) this.onReconnect();
  1651. }
  1652. };
  1653. /**
  1654. * The reconnection is done using an exponential back off algorithm to prevent
  1655. * the server from being flooded with connection requests. When the transport
  1656. * is disconnected we wait until the `reconnectionDelay` finishes. We multiply
  1657. * the `reconnectionDelay` (if the previous `reconnectionDelay` was 500 it will
  1658. * be updated to 1000 and than 2000>4000>8000>16000 etc.) and tell the current
  1659. * transport to connect again. When we run out of `reconnectionAttempts` we will
  1660. * do one final attempt and loop over all enabled transport methods to see if
  1661. * other transports might work. If everything fails we emit the `reconnect_failed`
  1662. * event.
  1663. *
  1664. * @api private
  1665. */
  1666. Socket.prototype.onReconnect = function(){
  1667. this.reconnecting = true;
  1668. this.reconnectionAttempts = 0;
  1669. this.reconnectionDelay = this.options.reconnectionDelay;
  1670. var self = this
  1671. , tryTransportsOnConnectTimeout = this.options.tryTransportsOnConnectTimeout
  1672. , rememberTransport = this.options.rememberTransport;
  1673. function reset(){
  1674. if(self.connected) self.emit('reconnect',[self.transport.type,self.reconnectionAttempts]);
  1675. self.removeEvent('connect_failed', maybeReconnect).removeEvent('connect', maybeReconnect);
  1676. self.reconnecting = false;
  1677. delete self.reconnectionAttempts;
  1678. delete self.reconnectionDelay;
  1679. delete self.reconnectionTimer;
  1680. delete self.redoTransports;
  1681. self.options.tryTransportsOnConnectTimeout = tryTransportsOnConnectTimeout;
  1682. self.options.rememberTransport = rememberTransport;
  1683. return;
  1684. };
  1685. function maybeReconnect(){
  1686. if (!self.reconnecting) return;
  1687. if (!self.connected){
  1688. if (self.connecting && self.reconnecting) return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1689. if (self.reconnectionAttempts++ >= self.options.maxReconnectionAttempts){
  1690. if (!self.redoTransports){
  1691. self.on('connect_failed', maybeReconnect);
  1692. self.options.tryTransportsOnConnectTimeout = true;
  1693. self.transport = self.getTransport(self.options.transports); // override with all enabled transports
  1694. self.redoTransports = true;
  1695. self.connect();
  1696. } else {
  1697. self.emit('reconnect_failed');
  1698. reset();
  1699. }
  1700. } else {
  1701. self.reconnectionDelay *= 2; // exponential back off
  1702. self.connect();
  1703. self.emit('reconnecting', [self.reconnectionDelay,self.reconnectionAttempts]);
  1704. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1705. }
  1706. } else {
  1707. reset();
  1708. }
  1709. };
  1710. this.options.tryTransportsOnConnectTimeout = false;
  1711. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1712. this.on('connect', maybeReconnect);
  1713. };
  1714. /**
  1715. * API compatiblity
  1716. */
  1717. Socket.prototype.fire = Socket.prototype.emit;
  1718. Socket.prototype.addListener = Socket.prototype.addEvent = Socket.prototype.addEventListener = Socket.prototype.on;
  1719. Socket.prototype.removeListener = Socket.prototype.removeEventListener = Socket.prototype.removeEvent;
  1720. })();
  1721. /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
  1722. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  1723. */
  1724. 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}}}}();
  1725. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  1726. // License: New BSD License
  1727. // Reference: http://dev.w3.org/html5/websockets/
  1728. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
  1729. (function() {
  1730. if (window.WebSocket) return;
  1731. var console = window.console;
  1732. if (!console || !console.log || !console.error) {
  1733. console = {log: function(){ }, error: function(){ }};
  1734. }
  1735. if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
  1736. console.error("Flash Player >= 10.0.0 is required.");
  1737. return;
  1738. }
  1739. if (location.protocol == "file:") {
  1740. console.error(
  1741. "WARNING: web-socket-js doesn't work in file:///... URL " +
  1742. "unless you set Flash Security Settings properly. " +
  1743. "Open the page via Web server i.e. http://...");
  1744. }
  1745. /**
  1746. * This class represents a faux web socket.
  1747. * @param {string} url
  1748. * @param {array or string} protocols
  1749. * @param {string} proxyHost
  1750. * @param {int} proxyPort
  1751. * @param {string} headers
  1752. */
  1753. WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
  1754. var self = this;
  1755. self.__id = WebSocket.__nextId++;
  1756. WebSocket.__instances[self.__id] = self;
  1757. self.readyState = WebSocket.CONNECTING;
  1758. self.bufferedAmount = 0;
  1759. self.__events = {};
  1760. if (!protocols) {
  1761. protocols = [];
  1762. } else if (typeof protocols == "string") {
  1763. protocols = [protocols];
  1764. }
  1765. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  1766. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  1767. setTimeout(function() {
  1768. WebSocket.__addTask(function() {
  1769. WebSocket.__flash.create(
  1770. self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
  1771. });
  1772. }, 0);
  1773. };
  1774. /**
  1775. * Send data to the web socket.
  1776. * @param {string} data The data to send to the socket.
  1777. * @return {boolean} True for success, false for failure.
  1778. */
  1779. WebSocket.prototype.send = function(data) {
  1780. if (this.readyState == WebSocket.CONNECTING) {
  1781. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  1782. }
  1783. // We use encodeURIComponent() here, because FABridge doesn't work if
  1784. // the argument includes some characters. We don't use escape() here
  1785. // because of this:
  1786. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  1787. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  1788. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  1789. // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
  1790. // additional testing.
  1791. var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
  1792. if (result < 0) { // success
  1793. return true;
  1794. } else {
  1795. this.bufferedAmount += result;
  1796. return false;
  1797. }
  1798. };
  1799. /**
  1800. * Close this web socket gracefully.
  1801. */
  1802. WebSocket.prototype.close = function() {
  1803. if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
  1804. return;
  1805. }
  1806. this.readyState = WebSocket.CLOSING;
  1807. WebSocket.__flash.close(this.__id);
  1808. };
  1809. /**
  1810. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1811. *
  1812. * @param {string} type
  1813. * @param {function} listener
  1814. * @param {boolean} useCapture
  1815. * @return void
  1816. */
  1817. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  1818. if (!(type in this.__events)) {
  1819. this.__events[type] = [];
  1820. }
  1821. this.__events[type].push(listener);
  1822. };
  1823. /**
  1824. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1825. *
  1826. * @param {string} type
  1827. * @param {function} listener
  1828. * @param {boolean} useCapture
  1829. * @return void
  1830. */
  1831. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  1832. if (!(type in this.__events)) return;
  1833. var events = this.__events[type];
  1834. for (var i = events.length - 1; i >= 0; --i) {
  1835. if (events[i] === listener) {
  1836. events.splice(i, 1);
  1837. break;
  1838. }
  1839. }
  1840. };
  1841. /**
  1842. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1843. *
  1844. * @param {Event} event
  1845. * @return void
  1846. */
  1847. WebSocket.prototype.dispatchEvent = function(event) {
  1848. var events = this.__events[event.type] || [];
  1849. for (var i = 0; i < events.length; ++i) {
  1850. events[i](event);
  1851. }
  1852. var handler = this["on" + event.type];
  1853. if (handler) handler(event);
  1854. };
  1855. /**
  1856. * Handles an event from Flash.
  1857. * @param {Object} flashEvent
  1858. */
  1859. WebSocket.prototype.__handleEvent = function(flashEvent) {
  1860. if ("readyState" in flashEvent) {
  1861. this.readyState = flashEvent.readyState;
  1862. }
  1863. if ("protocol" in flashEvent) {
  1864. this.protocol = flashEvent.protocol;
  1865. }
  1866. var jsEvent;
  1867. if (flashEvent.type == "open" || flashEvent.type == "error") {
  1868. jsEvent = this.__createSimpleEvent(flashEvent.type);
  1869. } else if (flashEvent.type == "close") {
  1870. // TODO implement jsEvent.wasClean
  1871. jsEvent = this.__createSimpleEvent("close");
  1872. } else if (flashEvent.type == "message") {
  1873. var data = decodeURIComponent(flashEvent.message);
  1874. jsEvent = this.__createMessageEvent("message", data);
  1875. } else {
  1876. throw "unknown event type: " + flashEvent.type;
  1877. }
  1878. this.dispatchEvent(jsEvent);
  1879. };
  1880. WebSocket.prototype.__createSimpleEvent = function(type) {
  1881. if (document.createEvent && window.Event) {
  1882. var event = document.createEvent("Event");
  1883. event.initEvent(type, false, false);
  1884. return event;
  1885. } else {
  1886. return {type: type, bubbles: false, cancelable: false};
  1887. }
  1888. };
  1889. WebSocket.prototype.__createMessageEvent = function(type, data) {
  1890. if (document.createEvent && window.MessageEvent && !window.opera) {
  1891. var event = document.createEvent("MessageEvent");
  1892. event.initMessageEvent("message", false, false, data, null, null, window, null);
  1893. return event;
  1894. } else {
  1895. // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
  1896. return {type: type, data: data, bubbles: false, cancelable: false};
  1897. }
  1898. };
  1899. /**
  1900. * Define the WebSocket readyState enumeration.
  1901. */
  1902. WebSocket.CONNECTING = 0;
  1903. WebSocket.OPEN = 1;
  1904. WebSocket.CLOSING = 2;
  1905. WebSocket.CLOSED = 3;
  1906. WebSocket.__flash = null;
  1907. WebSocket.__instances = {};
  1908. WebSocket.__tasks = [];
  1909. WebSocket.__nextId = 0;
  1910. /**
  1911. * Load a new flash security policy file.
  1912. * @param {string} url
  1913. */
  1914. WebSocket.loadFlashPolicyFile = function(url){
  1915. WebSocket.__addTask(function() {
  1916. WebSocket.__flash.loadManualPolicyFile(url);
  1917. });
  1918. };
  1919. /**
  1920. * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
  1921. */
  1922. WebSocket.__initialize = function() {
  1923. if (WebSocket.__flash) return;
  1924. if (WebSocket.__swfLocation) {
  1925. // For backword compatibility.
  1926. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  1927. }
  1928. if (!window.WEB_SOCKET_SWF_LOCATION) {
  1929. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  1930. return;
  1931. }
  1932. var container = document.createElement("div");
  1933. container.id = "webSocketContainer";
  1934. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  1935. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  1936. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  1937. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  1938. // the best we can do as far as we know now.
  1939. container.style.position = "absolute";
  1940. if (WebSocket.__isFlashLite()) {
  1941. container.style.left = "0px";
  1942. container.style.top = "0px";
  1943. } else {
  1944. container.style.left = "-100px";
  1945. container.style.top = "-100px";
  1946. }
  1947. var holder = document.createElement("div");
  1948. holder.id = "webSocketFlash";
  1949. container.appendChild(holder);
  1950. document.body.appendChild(container);
  1951. // See this article for hasPriority:
  1952. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  1953. swfobject.embedSWF(
  1954. WEB_SOCKET_SWF_LOCATION,
  1955. "webSocketFlash",
  1956. "1" /* width */,
  1957. "1" /* height */,
  1958. "10.0.0" /* SWF version */,
  1959. null,
  1960. null,
  1961. {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
  1962. null,
  1963. function(e) {
  1964. if (!e.success) {
  1965. console.error("[WebSocket] swfobject.embedSWF failed");
  1966. }
  1967. });
  1968. };
  1969. /**
  1970. * Called by Flash to notify JS that it's fully loaded and ready
  1971. * for communication.
  1972. */
  1973. WebSocket.__onFlashInitialized = function() {
  1974. // We need to set a timeout here to avoid round-trip calls
  1975. // to flash during the initialization process.
  1976. setTimeout(function() {
  1977. WebSocket.__flash = document.getElementById("webSocketFlash");
  1978. WebSocket.__flash.setCallerUrl(location.href);
  1979. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  1980. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  1981. WebSocket.__tasks[i]();
  1982. }
  1983. WebSocket.__tasks = [];
  1984. }, 0);
  1985. };
  1986. /**
  1987. * Called by Flash to notify WebSockets events are fired.
  1988. */
  1989. WebSocket.__onFlashEvent = function() {
  1990. setTimeout(function() {
  1991. try {
  1992. // Gets events using receiveEvents() instead of getting it from event object
  1993. // of Flash event. This is to make sure to keep message order.
  1994. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  1995. var events = WebSocket.__flash.receiveEvents();
  1996. for (var i = 0; i < events.length; ++i) {
  1997. WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
  1998. }
  1999. } catch (e) {
  2000. console.error(e);
  2001. }
  2002. }, 0);
  2003. return true;
  2004. };
  2005. // Called by Flash.
  2006. WebSocket.__log = function(message) {
  2007. console.log(decodeURIComponent(message));
  2008. };
  2009. // Called by Flash.
  2010. WebSocket.__error = function(message) {
  2011. console.error(decodeURIComponent(message));
  2012. };
  2013. WebSocket.__addTask = function(task) {
  2014. if (WebSocket.__flash) {
  2015. task();
  2016. } else {
  2017. WebSocket.__tasks.push(task);
  2018. }
  2019. };
  2020. /**
  2021. * Test if the browser is running flash lite.
  2022. * @return {boolean} True if flash lite is running, false otherwise.
  2023. */
  2024. WebSocket.__isFlashLite = function() {
  2025. if (!window.navigator || !window.navigator.mimeTypes) {
  2026. return false;
  2027. }
  2028. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  2029. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
  2030. return false;
  2031. }
  2032. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  2033. };
  2034. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  2035. if (window.addEventListener) {
  2036. window.addEventListener("load", function(){
  2037. WebSocket.__initialize();
  2038. }, false);
  2039. } else {
  2040. window.attachEvent("onload", function(){
  2041. WebSocket.__initialize();
  2042. });
  2043. }
  2044. }
  2045. })();