0

I have a cluster.js with the following code:

var numOfCpus = 16;
var cluster = require('cluster');
if (cluster.isMaster) {
    for (var i = 0; i < numOfCpus; i++) {
        cluster.fork();
    }
    console.log("master is running");
} else {
    console.log('Worker %d started', cluster.worker.id);

    var server = app.listen(8887);
    var io = require('socket.io').listen(server);

    var live_data = io.of('/live_data');
    live_data.on('connection',function(socket){
        console.log('Connected: %s', socket.id);
    });
}

My client application works fine when the numOfCpus = 1 in cluster.js. When I have anything more than 1, the socket.io starts giving the following error:

enter image description here

Do I have to do anything special to make socket.io work with multiple node workers? Any help will be highly appreciated. Thanks.

Kshitij Mittal
  • 2,698
  • 3
  • 25
  • 40

1 Answers1

1

The issue was solved using sticky session, as pointed by robertklep, in the comment. However, the package I used for the purpose is socketio-sticky-session.

My Final code of cluster.js looks like the following:

var sticky = require('socketio-sticky-session')
var cluster = require('cluster');
var os = require('os');
var options = {
    proxy: false,
    num: require('os').cpus().length
}

var server = sticky(options, function() {

    var server = app.listen();
    var io = require('socket.io').listen(server);

    var live_data = io.of('/live_data');
    live_data.on('connection',function(socket){
        console.log('Connected: %s', socket.id);
    });

    return server

}).listen(8887, function() {
console.log((cluster.worker ? 'WORKER ' + cluster.worker.id : 'MASTER') + ' | HOST ' + os.hostname() + ' | PORT ' + 8887)
})

Details about the working and implementation of sticky sessions can be read @ https://github.com/elad/node-cluster-socket.io

Kshitij Mittal
  • 2,698
  • 3
  • 25
  • 40