Skip to content

Instantly share code, notes, and snippets.

@formula1
Created November 9, 2014 21:22
Show Gist options
  • Save formula1/797e3ecba0d660bcfc49 to your computer and use it in GitHub Desktop.
Save formula1/797e3ecba0d660bcfc49 to your computer and use it in GitHub Desktop.
An Example of a Possible Websocket Application
function Application(href){
EventEmitter.call(this);
this.href = href;
var that = this;
socket.on("open", function(){
while(that.backlog.length > 0)
that.socket.send(that.backlog.shift());
that.emitEvent("open",arguments)
})
socket.on("message", function(msg,flags){
that.emitEvent("message",that.processRecieveMessage(msg));
})
socket.on("close", function(){
that.emitEvent("close",arguments)
});
this.socket = socket;
this.cache = {};
this.backlog = [];
Object.defineProperty(this, "open", {
get: function() {return that.socket.readyState == WebSocket.OPEN },
set: function(y) {}
});
if(this.socket.readyState == WebSocket.OPEN)
setTimeout(function(){that.emitEvent("open")}, 1);
}
Application.prototype = Object.create(EventEmitter.prototype);
Application.prototype.constructor = Application;
Application.prototype.serverProperty = function(property_name){
if(property_name in this)
throw new Error("Attempting to overwrite property: "+property_name);
var that = this;
Object.defineProperty(this, property_name, {
get: function() {return that.cache[property_name].value },
set: function(y) {
that.cache[property_name] = y;
y = that.processSendMessage(y);
if(this.socket.readyState == WebSocket.OPEN)
that.socket.send(y)
else
that.backlog.push(y);
}
})
}
Application.prototype.processSendMessage = function(msg){
//your code here
}
Application.prototype.processRecieveMessage = function(msg){
//your code here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment