Skip to content Skip to sidebar Skip to footer

Socket.io Websocket Authorization Failing When Clustering Node Application

Question: Is it possible to cluster an application which is using Socket.io for WebSocket support? If so what would be the best method of implementation? I've built an application

Solution 1:

What is your sessionStore? If it's the MemoryStore shipped with connect, then sessions won't be shared between your workers. Each worker will have it's own set of sessions, and if a client connects to another worker, you wont find their session. I suggest you take a look at e.g. connect-redis for sharing sessions between processes. Basic usage:

var connect = require('connect')
  , RedisStore = require('connect-redis')(connect);

var app = connect.createServer();
app.use(connect.session({store: new RedisStore, secret: 'top secret'});

Of course, this requires that you also set up redis. Over at the Connect wiki there are modules for CouchDB, memcached, postgres and others.

This only solves part of your problem, though, because now you have sessions shared between workers, but socket.io has no way of sending messages to clients which are connected to other workers. Basically, if you issue a socket.emit in one worker, that message will only be sent to clients connected to that same worker. One solution to this is to use RedisStore for socket.io, which leverages redis to route messages between workers. Basic usage:

var sio = require('socket.io')
  , RedisStore = sio.RedisStore
  , io = sio.listen(app);

io.set('store', new RedisStore);

Now, all messages should be routed to clients no matter what worker they are connected to.

See also: Node.js, multi-threading and Socket.io

Post a Comment for "Socket.io Websocket Authorization Failing When Clustering Node Application"