Full stack pub/sub with SocketCluster

I have been working on a module called SocketCluster (https://github.com/topcloud/socketcluster) which allows developers to build robust and highly scalable realtime systems. It basically allows you to run your Node.js code on multiple CPU cores in parallel – It also handles a lot of tedious things like multi-process error logging, respawning dead workers, reconnecting clients whose connections drop out, etc… SC ‘s realtime features allow you to extend pub/sub all the way to the browser.

sc_architecture

This diagram is a bit generic, but you could assume that channel 1, channel 2, channel 3… represent different chat rooms which clients can join – Each room could focus on a particular topic, for example let’s say ‘math’, ‘physics’, ‘chemistry’… To listen to all messages posted in the room ‘physics’, all you have to do on the client is call: socket.on(‘physics’, function (data) {…}). To send messages to the physics room; you would just call socket.publish(‘physics’, messageData). SocketCluster lets you specify middleware on the server to allow or block specific users from subscribing, publishing or emitting certain events. Examples:

scServer.addMiddleware(scServer.MIDDLEWARE_SUBSCRIBE, function (socket, event, next) {
    // ...
    if (...) {
        next(); // Allow
    } else {
        next(socket.id + ' is not allowed to subscribe to ' + event); // Block
    }
});


scServer.addMiddleware(scServer.MIDDLEWARE_PUBLISH, function (socket, channel, data, next) {
    // ...
    if (...) {
        next(); // Allow
    } else {
        next(socket.id + ' is not allowed to publish the ' + event + ' event'); // Block
    }
});


scServer.addMiddleware(scServer.MIDDLEWARE_EMIT, function (socket, event, data, next) {
    // ...
    if (...) {
        next(); // Allow
    } else {
        next(socket.id + ' is not allowed to emit the ' + event + ' event'); // Block
    }
});

SocketCluster also exposes a Global object on the server-side (scServer.global) through which you can publish events to clients:

scServer.global.publish(eventName, data, cb);

An emitted event is only sent to the other side of the socket (I.e. server => client or client => server); on the other hand, a published event will be sent to all subscribed client sockets (and nobody else!).
To subscribe a client socket to an event, you just use:

socket.on(eventName, listenerFn);

^ SocketCluster will automatically send a subscription request the server (it will have to pass through the SUBSCRIBE middleware first though!).

Advertisements