sync/www/assets/js/notwebsocket.js

92 lines
2.4 KiB
JavaScript
Raw Normal View History

var NotWebsocket = function() {
this.connected = false;
$.getJSON(WEB_URL + "/nws/connect", function(data) {
2013-06-04 15:46:06 +00:00
console.log(data);
this.hash = data;
this.connected = true;
this.recv(["connect", undefined]);
this.pollint = setInterval(function() {
this.poll();
2013-06-04 16:11:16 +00:00
}.bind(this), 100);
}.bind(this));
this.handlers = {};
}
2013-06-04 15:46:06 +00:00
NotWebsocket.prototype.reconnect = function() {
$.getJSON(WEB_URL + "/nws/connect", function(data) {
this.hash = data;
this.connected = true;
this.recv(["connect", undefined]);
this.pollint = setInterval(function() {
this.poll();
}.bind(this), 100);
}.bind(this))
.fail(function() {
if(this.reconndelay < 10000)
this.reconndelay += 100;
setTimeout(function() {
this.reconnect();
}.bind(this), this.reconndelay);
}.bind(this));
}
NotWebsocket.prototype.emit = function(msg, data) {
if(!this.connected) {
setTimeout(function() {
this.emit(msg, data);
}.bind(this), 100);
2013-06-04 15:46:06 +00:00
return;
}
var pkt = [msg, data];
2013-06-04 15:46:06 +00:00
var str = escape(JSON.stringify(pkt)).replace(/\//g, "%2F");
$.getJSON(WEB_URL+"/nws/"+this.hash+"/"+str, function(){});
}
NotWebsocket.prototype.on = function(msg, callback) {
if(!(msg in this.handlers))
this.handlers[msg] = [];
this.handlers[msg].push(callback);
}
NotWebsocket.prototype.poll = function() {
if(!this.connected)
return;
2013-06-04 16:11:16 +00:00
if(this.polling)
return false;
$.getJSON(WEB_URL+"/nws/"+this.hash+"/poll?callback=?", function(data) {
this.polling = true;
for(var i = 0; i < data.length; i++) {
2013-06-04 15:46:06 +00:00
try {
this.recv(data[i]);
}
catch(e) { }
}
2013-06-04 16:11:16 +00:00
this.polling = false;
2013-06-04 15:46:06 +00:00
}.bind(this))
.fail(function() {
2013-06-04 16:11:16 +00:00
console.log(arguments);
2013-06-04 15:46:06 +00:00
this.disconnect();
}.bind(this));
}
NotWebsocket.prototype.recv = function(pkt) {
var msg = pkt[0], data = pkt[1];
2013-06-04 15:46:06 +00:00
if(!(msg in this.handlers)) {
return;
2013-06-04 15:46:06 +00:00
}
for(var i = 0; i < this.handlers[msg].length; i++) {
this.handlers[msg][i](data);
}
}
2013-06-04 15:46:06 +00:00
NotWebsocket.prototype.disconnect = function() {
this.recv(["disconnect", undefined]);
clearInterval(this.pollint);
this.connected = false;
2013-06-04 16:11:16 +00:00
this.reconndelay = 1000;
setTimeout(function() {
this.reconnect();
}.bind(this), this.reconndelay);
2013-06-04 15:46:06 +00:00
}