App-SocialCalc-Multiplayer
view release on metacpan or search on metacpan
socialcalc/third-party/Socket.IO-node/support/socket.io-client/socket.io.js view on Meta::CPAN
// WEB_SOCKET_SWF_LOCATION = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cdn.socket.io/' + this.io.version + '/WebSocketMain.swf';
if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined')
WEB_SOCKET_SWF_LOCATION = '/socket.io/lib/vendor/web-socket-js/WebSocketMain.swf';
}
/**
* socket.io-node-client
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function(){
var io = this.io,
/**
* Set when the `onload` event is executed on the page. This variable is used by
* `io.util.load` to detect if we need to execute the function immediately or add
* it to a onload listener.
*
* @type {Boolean}
* @api private
*/
pageLoaded = false;
/**
* @namespace
*/
io.util = {
/**
* Executes the given function when the page is loaded.
*
* Example:
*
* io.util.load(function(){ console.log('page loaded') });
*
* @param {Function} fn
* @api public
*/
load: function(fn){
if (/loaded|complete/.test(document.readyState) || pageLoaded) return fn();
if ('attachEvent' in window){
window.attachEvent('onload', fn);
} else {
window.addEventListener('load', fn, false);
}
},
/**
* Defers the function untill it's the function can be executed without
* blocking the load process. This is especially needed for WebKit based
* browsers. If a long running connection is made before the onload event
* a loading indicator spinner will be present at all times untill a
* reconnect has been made.
*
* @param {Function} fn
* @api public
*/
defer: function(fn){
if (!io.util.webkit) return fn();
io.util.load(function(){
setTimeout(fn,100);
});
},
/**
* Inherit the prototype methods from one constructor into another.
*
* Example:
*
* function foo(){};
* foo.prototype.hello = function(){ console.log( this.words )};
*
* function bar(){
* this.words = "Hello world";
* };
*
* io.util.inherit(bar,foo);
* var person = new bar();
* person.hello();
* // => "Hello World"
*
* @param {Constructor} ctor The constructor that needs to inherit the methods.
* @param {Constructor} superCtor The constructor to inherit from.
* @api public
*/
inherit: function(ctor, superCtor){
// no support for `instanceof` for now
for (var i in superCtor.prototype){
ctor.prototype[i] = superCtor.prototype[i];
}
},
/**
* Finds the index of item in a given Array.
*
* Example:
*
* var data = ['socket',2,3,4,'socket',5,6,7,'io'];
* io.util.indexOf(data,'socket',1);
* // => 4
*
* @param {Array} arr The array
* @param item The item that we need to find
* @param {Integer} from Starting point
* @api public
*/
indexOf: function(arr, item, from){
for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){
if (arr[i] === item) return i;
}
return -1;
},
/**
* Checks if the given object is an Array.
*
* Example:
*
* io.util.isArray([]);
* // => true
* io.util.isArray({});
socialcalc/third-party/Socket.IO-node/support/socket.io-client/socket.io.js view on Meta::CPAN
throw new Error('Missing disconnect() implementation');
};
/**
* Encode the message by adding the `frame` to each message. This allows
* the client so send multiple messages with only one request.
*
* @param {String|Array} messages Messages that need to be encoded.
* @returns {String} Encoded message.
* @api private
*/
Transport.prototype.encode = function(messages){
var ret = '', message;
messages = io.util.isArray(messages) ? messages : [messages];
for (var i = 0, l = messages.length; i < l; i++){
message = messages[i] === null || messages[i] === undefined ? '' : stringify(messages[i]);
ret += frame + message.length + frame + message;
}
return ret;
};
/**
* Decoded the response from the Socket.IO server, as the server could send multiple
* messages in one response.
*
* @param (String} data The response from the server that requires decoding
* @returns {Array} Decoded messages.
* @api private
*/
Transport.prototype.decode = function(data){
var messages = [], number, n;
do {
if (data.substr(0, 3) !== frame) return messages;
data = data.substr(3);
number = '', n = '';
for (var i = 0, l = data.length; i < l; i++){
n = Number(data.substr(i, 1));
if (data.substr(i, 1) == n){
number += n;
} else {
data = data.substr(number.length + frame.length);
number = Number(number);
break;
}
}
messages.push(data.substr(0, number)); // here
data = data.substr(number);
} while(data !== '');
return messages;
};
/**
* Handles the response from the server. When a new response is received
* it will automatically update the timeout, decode the message and
* forwards the response to the onMessage function for further processing.
*
* @param {String} data Response from the server.
* @api private
*/
Transport.prototype.onData = function(data){
this.setTimeout();
var msgs = this.decode(data);
if (msgs && msgs.length){
for (var i = 0, l = msgs.length; i < l; i++){
this.onMessage(msgs[i]);
}
}
};
/**
* All the transports have a dedicated timeout to detect if
* the connection is still alive. We clear the existing timer
* and set new one each time this function is called. When the
* timeout does occur it will call the `onTimeout` method.
*
* @api private
*/
Transport.prototype.setTimeout = function(){
var self = this;
if (this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(function(){
self.onTimeout();
}, this.options.timeout);
};
/**
* Disconnect from the Socket.IO server when a timeout occurs.
*
* @api private
*/
Transport.prototype.onTimeout = function(){
this.onDisconnect();
};
/**
* After the response from the server has been parsed to individual
* messages we need to decode them using the the Socket.IO message
* protocol: <https://github.com/learnboost/socket.io-node/>.
*
* When a message is received we check if a session id has been set,
* if the session id is missing we can assume that the received message
* contains the sessionid of the connection.
* When a message is prefixed with `~h~` we dispatch it our heartbeat
* processing method `onHeartbeat` with the content of the heartbeat.
*
* When the message is prefixed with `~j~` we can assume that the contents
* of the message is JSON encoded, so we parse the message and notify
* the base of the new message.
*
* If none of the above, we consider it just a plain text message and
* notify the base of the new message.
*
* @param {String} message A decoded message from the server.
* @api private
*/
Transport.prototype.onMessage = function(message){
if (!this.sessionid){
this.sessionid = message;
this.onConnect();
} else if (message.substr(0, 3) == '~h~'){
this.onHeartbeat(message.substr(3));
} else if (message.substr(0, 3) == '~j~'){
this.base.onMessage(JSON.parse(message.substr(3)));
} else {
this.base.onMessage(message);
}
},
/**
* Send the received heartbeat message back to server. So the server
* knows we are still connected.
*
* @param {String} heartbeat Heartbeat response from the server.
* @api private
*/
Transport.prototype.onHeartbeat = function(heartbeat){
this.send('~h~' + heartbeat); // echo
};
/**
* Notifies the base when a connection to the Socket.IO server has
* been established. And it starts the connection `timeout` timer.
*
* @api private
*/
Transport.prototype.onConnect = function(){
this.connected = true;
this.connecting = false;
this.base.onConnect();
this.setTimeout();
};
/**
* Notifies the base when the connection with the Socket.IO server
* has been disconnected.
*
* @api private
*/
Transport.prototype.onDisconnect = function(){
this.connecting = false;
this.connected = false;
this.sessionid = null;
this.base.onDisconnect();
};
/**
* Generates a connection url based on the Socket.IO URL Protocol.
* See <https://github.com/learnboost/socket.io-node/> for more details.
*
* @returns {String} Connection url
* @api private
*/
Transport.prototype.prepareUrl = function(){
return (this.base.options.secure ? 'https' : 'http')
+ '://' + this.base.host
+ ':' + this.base.options.port
+ '/' + this.base.options.resource
+ '/' + this.type
+ (this.sessionid ? ('/' + this.sessionid) : '/');
};
})();
/**
* socket.io-node-client
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function(){
var io = this.io,
/**
* A small stub function that will be used to reduce memory leaks.
*
* @type {Function}
* @api private
*/
empty = new Function,
/**
* We preform a small feature detection to see if `Cross Origin Resource Sharing`
* is supported in the `XMLHttpRequest` object, so we can use it for cross domain requests.
*
* @type {Boolean}
* @api private
*/
XMLHttpRequestCORS = (function(){
if (!('XMLHttpRequest' in window)) return false;
// CORS feature detection
var a = new XMLHttpRequest();
socialcalc/third-party/Socket.IO-node/support/socket.io-client/socket.io.js view on Meta::CPAN
self.onDisconnect();
};
this.insertAt.parentNode.insertBefore(script, this.insertAt);
this.script = script;
};
/**
* Callback function for the incoming message stream from the Socket.IO server.
*
* @param {String} data The message
* @param {document} doc Reference to the context
* @api private
*/
JSONPPolling.prototype._ = function(){
this.onData.apply(this, arguments);
this.get();
return this;
};
/**
* Checks if browser supports this transport.
*
* @return {Boolean}
* @api public
*/
JSONPPolling.check = function(){
return true;
};
/**
* Check if cross domain requests are supported
*
* @returns {Boolean}
* @api public
*/
JSONPPolling.xdomainCheck = function(){
return true;
};
})();
/**
* socket.io-node-client
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function(){
var io = this.io;
/**
* Create a new `Socket.IO client` which can establish a persisted
* connection with a Socket.IO enabled server.
*
* Options:
* - `secure` Use secure connections, defaulting to false.
* - `document` Reference to the document object to retrieve and set cookies, defaulting to document.
* - `port` The port where the Socket.IO server listening on, defaulting to location.port.
* - `resource` The path or namespace on the server where the Socket.IO requests are intercepted, defaulting to 'socket.io'.
* - `transports` A ordered list with the available transports, defaulting to all transports.
* - `transportOption` A {Object} containing the options for each transport. The key of the object should reflect
* name of the transport and the value a {Object} with the options.
* - `connectTimeout` The duration in milliseconds that a transport has to establish a working connection, defaulting to 5000.
* - `tryTransportsOnConnectTimeout` Should we attempt other transport methods when the connectTimeout occurs, defaulting to true.
* - `reconnect` Should reconnection happen automatically, defaulting to true.
* - `reconnectionDelay` The delay in milliseconds before we attempt to establish a working connection. This value will
* increase automatically using a exponential back off algorithm. Defaulting to 500.
* - `maxReconnectionAttempts` Number of attempts we should make before seizing the reconnect operation, defaulting to 10.
* - `rememberTransport` Should the successfully connected transport be remembered in a cookie, defaulting to true.
*
* Examples:
*
* Create client with the default settings.
*
* var socket = new io.Socket();
* socket.connect();
* socket.on('message', function(msg){
* console.log('Received message: ' + msg );
* });
* socket.on('connect', function(){
* socket.send('Hello from client');
* });
*
* Create a connection with server on a different port and host.
*
* var socket = new io.Socket('http://example.com',{port:1337});
*
* @constructor
* @exports Socket as io.Socket
* @param {String} [host] The host where the Socket.IO server is located, it defaults to the host that runs the page.
* @param {Objects} [options] The options that will configure the Socket.IO client.
* @property {String} host The supplied host arguments or the host that page runs.
* @property {Object} options The passed options combined with the defaults.
* @property {Boolean} connected Whether the socket is connected or not.
* @property {Boolean} connecting Whether the socket is connecting or not.
* @property {Boolean} reconnecting Whether the socket is reconnecting or not.
* @property {Object} transport The selected transport instance.
* @api public
*/
var Socket = io.Socket = function(host, options){
this.host = host || document.domain;
this.options = {
secure: false,
document: document,
port: document.location.port || 80,
resource: 'socket.io',
transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
transportOptions: {
'xhr-polling': {
timeout: 25000 // based on polling duration default
},
'jsonp-polling': {
timeout: 25000
}
},
connectTimeout: 5000,
tryTransportsOnConnectTimeout: true,
reconnect: true,
reconnectionDelay: 500,
maxReconnectionAttempts: 10,
rememberTransport: true
};
io.util.merge(this.options, options);
this.connected = false;
this.connecting = false;
this.reconnecting = false;
this.events = {};
this.transport = this.getTransport();
if (!this.transport && 'console' in window) console.error('No transport available');
};
/**
* Find an available transport based on the options supplied in the constructor. For example if the
* `rememberTransport` option was set we will only connect with the previous successfully connected transport.
* The supplied transports can be overruled if the `override` argument is supplied.
*
* Example:
*
* Override the existing transports.
*
* var socket = new io.Socket();
* socket.getTransport(['jsonp-polling','websocket']);
* // returns the json-polling transport because it's availabe in all browsers.
*
* @param {Array} [override] A ordered list with transports that should be used instead of the options.transports.
* @returns {Null|Transport} The available transport.
* @api private
*/
Socket.prototype.getTransport = function(override){
var transports = override || this.options.transports, match;
if (this.options.rememberTransport && !override){
match = this.options.document.cookie.match('(?:^|;)\\s*socketio=([^;]*)');
if (match){
this.rememberedTransport = true;
transports = [decodeURIComponent(match[1])];
}
}
for (var i = 0, transport; transport = transports[i]; i++){
if (io.Transport[transport]
&& io.Transport[transport].check()
&& (!this.isXDomain() || io.Transport[transport].xdomainCheck())){
return new io.Transport[transport](this, this.options.transportOptions[transport] || {});
}
}
return null;
};
/**
* Establish a new connection with the Socket.IO server. This is done using the selected transport by the
* getTransport method. If the `connectTimeout` and the `tryTransportsOnConnectTimeout` options are set
* the client will keep trying to connect to the server using a different transports when the timeout occurs.
*
* Example:
*
* Create a Socket.IO client with a connect callback (We assume we have the WebSocket transport avaliable).
*
* var socket = new io.Socket();
* socket.connect(function(transport){
* console.log("Connected to server using the " + socket.transport.type + " transport.");
* });
* // => "Connected to server using the WebSocket transport."
*
* @param {Function} [fn] Callback.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.connect = function(fn){
if (this.transport && !this.connected){
if (this.connecting) this.disconnect(true);
this.connecting = true;
this.emit('connecting', [this.transport.type]);
this.transport.connect();
if (this.options.connectTimeout){
var self = this;
this.connectTimeoutTimer = setTimeout(function(){
if (!self.connected){
self.disconnect(true);
if (self.options.tryTransportsOnConnectTimeout && !self.rememberedTransport){
if(!self.remainingTransports) self.remainingTransports = self.options.transports.slice(0);
var transports = self.remainingTransports;
while(transports.length > 0 && transports.splice(0,1)[0] != self.transport.type){}
if(transports.length){
self.transport = self.getTransport(transports);
self.connect();
}
}
if(!self.remainingTransports || self.remainingTransports.length == 0) self.emit('connect_failed');
}
if(self.remainingTransports && self.remainingTransports.length == 0) delete self.remainingTransports;
}, this.options.connectTimeout);
}
}
if (fn && typeof fn == 'function') this.once('connect',fn);
return this;
};
/**
* Sends the data to the Socket.IO server. If there isn't a connection to the server
* the data will be forwarded to the queue.
*
* @param {Mixed} data The data that needs to be send to the Socket.IO server.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.send = function(data){
if (!this.transport || !this.transport.connected) return this.queue(data);
this.transport.send(data);
return this;
};
/**
* Disconnect the established connect.
*
* @param {Boolean} [soft] A soft disconnect will keep the reconnect settings enabled.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.disconnect = function(soft){
if (this.connectTimeoutTimer) clearTimeout(this.connectTimeoutTimer);
if (!soft) this.options.reconnect = false;
this.transport.disconnect();
return this;
};
/**
* Adds a new eventListener for the given event.
*
* Example:
*
* var socket = new io.Socket();
* socket.on("connect", function(transport){
* console.log("Connected to server using the " + socket.transport.type + " transport.");
* });
* // => "Connected to server using the WebSocket transport."
*
* @param {String} name The name of the event.
* @param {Function} fn The function that is called once the event is emitted.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.on = function(name, fn){
if (!(name in this.events)) this.events[name] = [];
this.events[name].push(fn);
return this;
};
/**
* Adds a one time listener, the listener will be removed after the event is emitted.
*
* Example:
*
* var socket = new io.Socket();
* socket.once("custom:event", function(){
* console.log("I should only log once.");
* });
* socket.emit("custom:event");
* socket.emit("custom:event");
* // => "I should only log once."
*
* @param {String} name The name of the event.
* @param {Function} fn The function that is called once the event is emitted.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.once = function(name, fn){
var self = this
, once = function(){
self.removeEvent(name, once);
fn.apply(self, arguments);
};
once.ref = fn;
self.on(name, once);
return this;
};
/**
* Emit a event to all listeners.
*
* Example:
socialcalc/third-party/Socket.IO-node/support/socket.io-client/socket.io.js view on Meta::CPAN
* by calling this method so we can set the `connected` and `connecting` properties and emit
* the connection event.
*
* @api private
*/
Socket.prototype.onConnect = function(){
this.connected = true;
this.connecting = false;
this.doQueue();
if (this.options.rememberTransport) this.options.document.cookie = 'socketio=' + encodeURIComponent(this.transport.type);
this.emit('connect');
};
/**
* When the transport receives new messages from the Socket.IO server it notifies us by calling
* this method with the decoded `data` it received.
*
* @param data The message from the Socket.IO server.
* @api private
*/
Socket.prototype.onMessage = function(data){
this.emit('message', [data]);
};
/**
* When the transport is disconnected from the Socket.IO server it notifies us by calling
* this method. If we where connected and the `reconnect` is set we will attempt to reconnect.
*
* @api private
*/
Socket.prototype.onDisconnect = function(){
var wasConnected = this.connected;
this.connected = false;
this.connecting = false;
this.queueStack = [];
if (wasConnected){
this.emit('disconnect');
if (this.options.reconnect && !this.reconnecting) this.onReconnect();
}
};
/**
* The reconnection is done using an exponential back off algorithm to prevent
* the server from being flooded with connection requests. When the transport
* is disconnected we wait until the `reconnectionDelay` finishes. We multiply
* the `reconnectionDelay` (if the previous `reconnectionDelay` was 500 it will
* be updated to 1000 and than 2000>4000>8000>16000 etc.) and tell the current
* transport to connect again. When we run out of `reconnectionAttempts` we will
* do one final attempt and loop over all enabled transport methods to see if
* other transports might work. If everything fails we emit the `reconnect_failed`
* event.
*
* @api private
*/
Socket.prototype.onReconnect = function(){
this.reconnecting = true;
this.reconnectionAttempts = 0;
this.reconnectionDelay = this.options.reconnectionDelay;
var self = this
, tryTransportsOnConnectTimeout = this.options.tryTransportsOnConnectTimeout
, rememberTransport = this.options.rememberTransport;
function reset(){
if(self.connected) self.emit('reconnect',[self.transport.type,self.reconnectionAttempts]);
self.removeEvent('connect_failed', maybeReconnect).removeEvent('connect', maybeReconnect);
self.reconnecting = false;
delete self.reconnectionAttempts;
delete self.reconnectionDelay;
delete self.reconnectionTimer;
delete self.redoTransports;
self.options.tryTransportsOnConnectTimeout = tryTransportsOnConnectTimeout;
self.options.rememberTransport = rememberTransport;
return;
};
function maybeReconnect(){
if (!self.reconnecting) return;
if (!self.connected){
if (self.connecting && self.reconnecting) return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
if (self.reconnectionAttempts++ >= self.options.maxReconnectionAttempts){
if (!self.redoTransports){
self.on('connect_failed', maybeReconnect);
self.options.tryTransportsOnConnectTimeout = true;
self.transport = self.getTransport(self.options.transports); // override with all enabled transports
self.redoTransports = true;
self.connect();
} else {
self.emit('reconnect_failed');
reset();
}
} else {
self.reconnectionDelay *= 2; // exponential back off
self.connect();
self.emit('reconnecting', [self.reconnectionDelay,self.reconnectionAttempts]);
self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
}
} else {
reset();
}
};
this.options.tryTransportsOnConnectTimeout = false;
this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
this.on('connect', maybeReconnect);
};
/**
* API compatiblity
*/
Socket.prototype.fire = Socket.prototype.emit;
Socket.prototype.addListener = Socket.prototype.addEvent = Socket.prototype.addEventListener = Socket.prototype.on;
Socket.prototype.removeListener = Socket.prototype.removeEventListener = Socket.prototype.removeEvent;
})();
/* SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
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,...
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
(function() {
if (window.WebSocket) return;
var console = window.console;
if (!console || !console.log || !console.error) {
console = {log: function(){ }, error: function(){ }};
}
if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
console.error("Flash Player >= 10.0.0 is required.");
return;
}
if (location.protocol == "file:") {
console.error(
"WARNING: web-socket-js doesn't work in file:///... URL " +
"unless you set Flash Security Settings properly. " +
"Open the page via Web server i.e. http://...");
}
/**
* This class represents a faux web socket.
* @param {string} url
* @param {array or string} protocols
* @param {string} proxyHost
* @param {int} proxyPort
* @param {string} headers
*/
WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
var self = this;
self.__id = WebSocket.__nextId++;
WebSocket.__instances[self.__id] = self;
self.readyState = WebSocket.CONNECTING;
self.bufferedAmount = 0;
self.__events = {};
if (!protocols) {
protocols = [];
} else if (typeof protocols == "string") {
protocols = [protocols];
}
// Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
// Otherwise, when onopen fires immediately, onopen is called before it is set.
setTimeout(function() {
WebSocket.__addTask(function() {
WebSocket.__flash.create(
self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
});
}, 0);
};
/**
* Send data to the web socket.
* @param {string} data The data to send to the socket.
* @return {boolean} True for success, false for failure.
*/
WebSocket.prototype.send = function(data) {
if (this.readyState == WebSocket.CONNECTING) {
throw "INVALID_STATE_ERR: Web Socket connection has not been established";
}
// We use encodeURIComponent() here, because FABridge doesn't work if
// the argument includes some characters. We don't use escape() here
// because of this:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
// But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
// preserve all Unicode characters either e.g. "\uffff" in Firefox.
// Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
// additional testing.
var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
if (result < 0) { // success
return true;
} else {
this.bufferedAmount += result;
return false;
}
};
/**
* Close this web socket gracefully.
*/
WebSocket.prototype.close = function() {
if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
return;
}
this.readyState = WebSocket.CLOSING;
WebSocket.__flash.close(this.__id);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture
* @return void
*/
WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
if (!(type in this.__events)) {
this.__events[type] = [];
}
this.__events[type].push(listener);
};
/**
socialcalc/third-party/Socket.IO-node/support/socket.io-client/socket.io.js view on Meta::CPAN
/**
* Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
*/
WebSocket.__initialize = function() {
if (WebSocket.__flash) return;
if (WebSocket.__swfLocation) {
// For backword compatibility.
window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
}
if (!window.WEB_SOCKET_SWF_LOCATION) {
console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
return;
}
var container = document.createElement("div");
container.id = "webSocketContainer";
// Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
// Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
// But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
// Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
// the best we can do as far as we know now.
container.style.position = "absolute";
if (WebSocket.__isFlashLite()) {
container.style.left = "0px";
container.style.top = "0px";
} else {
container.style.left = "-100px";
container.style.top = "-100px";
}
var holder = document.createElement("div");
holder.id = "webSocketFlash";
container.appendChild(holder);
document.body.appendChild(container);
// See this article for hasPriority:
// http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
swfobject.embedSWF(
WEB_SOCKET_SWF_LOCATION,
"webSocketFlash",
"1" /* width */,
"1" /* height */,
"10.0.0" /* SWF version */,
null,
null,
{hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
null,
function(e) {
if (!e.success) {
console.error("[WebSocket] swfobject.embedSWF failed");
}
});
};
/**
* Called by Flash to notify JS that it's fully loaded and ready
* for communication.
*/
WebSocket.__onFlashInitialized = function() {
// We need to set a timeout here to avoid round-trip calls
// to flash during the initialization process.
setTimeout(function() {
WebSocket.__flash = document.getElementById("webSocketFlash");
WebSocket.__flash.setCallerUrl(location.href);
WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
for (var i = 0; i < WebSocket.__tasks.length; ++i) {
WebSocket.__tasks[i]();
}
WebSocket.__tasks = [];
}, 0);
};
/**
* Called by Flash to notify WebSockets events are fired.
*/
WebSocket.__onFlashEvent = function() {
setTimeout(function() {
try {
// Gets events using receiveEvents() instead of getting it from event object
// of Flash event. This is to make sure to keep message order.
// It seems sometimes Flash events don't arrive in the same order as they are sent.
var events = WebSocket.__flash.receiveEvents();
for (var i = 0; i < events.length; ++i) {
WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
}
} catch (e) {
console.error(e);
}
}, 0);
return true;
};
// Called by Flash.
WebSocket.__log = function(message) {
console.log(decodeURIComponent(message));
};
// Called by Flash.
WebSocket.__error = function(message) {
console.error(decodeURIComponent(message));
};
WebSocket.__addTask = function(task) {
if (WebSocket.__flash) {
task();
} else {
WebSocket.__tasks.push(task);
}
};
/**
* Test if the browser is running flash lite.
* @return {boolean} True if flash lite is running, false otherwise.
*/
WebSocket.__isFlashLite = function() {
if (!window.navigator || !window.navigator.mimeTypes) {
return false;
}
var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
return false;
}
return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
};
if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
if (window.addEventListener) {
window.addEventListener("load", function(){
WebSocket.__initialize();
}, false);
} else {
window.attachEvent("onload", function(){
WebSocket.__initialize();
});
}
}
( run in 0.713 second using v1.01-cache-2.11-cpan-39bf76dae61 )