Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bsstoner/527302 to your computer and use it in GitHub Desktop.
Save bsstoner/527302 to your computer and use it in GitHub Desktop.
/**
* SocketManager - Singleton to manage socket 'routing', live (in memory) sessions and message routing
*
* Requires Socket.IO-node and Socket.IO client libraries.
*
* Usage:
* in your main app.js file (or whereever you create the server)
*
* var io = require('socket.io'),
* sm = require('socketmanager');
*
* socket = io.listen(server); // or io.listen(app) in express
*
* sm.register(socket);
*
* // Then Register methods that will be run based on the 'msgType' attribute sent from the client in each message
* sm.on('joinChat', function(client, messageJSON){
* // do something here (i.e. send message back to client, broadcast something, etc.)
* });
*
*/
exports = function SocketManager(){
socket: null,
messageMethods: {},
sessions: {},
register: function(socket){
var context = this;
this.socket = socket;
this.socket.on('connection', function(client){
context.connect(client);
client.on('message', function(msg){
context.receive(client, msg);
});
client.on('disconnect', function(){
context.disconnect(client);
});
});
},
connect: function(client){
this.sessions[client.sessionId] = client;
},
disconnect: function(client){
delete this.sessions[client.sessionId];
},
receive: function(client, msg){
var parsed = JSON.parse(msg);
if (parsed.msgType && this.messageMethods[parsed.msgType]){
this.messageMethods[parsed.msgType](client, parsed);
}
},
on: function(methodName, closure){
this[methodName] = closure;
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment