Vadorequest
Vadorequest

Reputation: 18009

Node.js - Socket.io - What's the best way to organize sockets?

I've never used socket.io, I am wondering how I should build it inside my models, for the moment I plan to have a class Socket and another Model which would be derivated to be used in UserModel for instance.

Then, on UserModel.authenticate() I would call the socket to add the user in some room I guess.

I'm just wondering if it's the way to go or if I should respect some kind of design pattern or if my design is wrong. (no backward experience with socket so better ask people who have some!)

Let me know if you know a better approach or some kind of example, I think it is simple but I could be wrong.

Upvotes: 4

Views: 2413

Answers (1)

pedrommuller
pedrommuller

Reputation: 16066

What you are trying to implement sounds like facade pattern when trying to abstract the mechanics of the sockets.

In my opinion, that implementation can be very difficult to do so since you have to do a very good abstraction for the sockets, I got a totally different approach, how I do it is to separate the sockets grouping them by aggregates and responsibility, lets say I have a socket file that only will have user interaction other for managing activity streams (in the case of a social network) or managing products, etc. look at them as you were looking at controllers in the MVC pattern.

for separating the sockets into different physical files, you can manage event handlers by files like this:

io.of('namespace').on('connection',function(socket){
    var eventHandlers = {
        'user': new userLib.UserSocket(socket, app),
        'document': new documentLib.documentSocket(socket,app)
    };
    for (var category in eventHandlers) {
        var handler = eventHandlers[category].handlers;
        for (var event in handler) {
        socket.on(event, handler[event]);
        }
    }
    socket.on('error',function(err){
        console.error(err);
    });
    socket.on('disconnect',function(){
         console.log('disconnect');
    });

}

in your user event handler file (ex user.socket.js):

var signup = function(){
    var self = this; 
    //TODO: do your code
};

var authenticate = function(){
var self = this; 
    //TODO: do your code
}

exports.UserSocket = function(socket,app){
    this.app = app;
    this.socket = socket;

    this.handlers = {
        authenticate:authenticate.bind(this),
        signup: signup.bind(this)
    };
};

Hope that helps!

Upvotes: 3

Related Questions