Using socket.io with redis as a cluster

62 views Asked by At

I am trying to implement a cluster for my socket.io app using redis due to the fact i would like to take advantage of all cores in the server and not only one but also be able to scale out with more servers in the future if necessary.

If i have understood it correctly i will need the following modules to get this working.

  • sticky-session (Balancing requests using their IP address. Thus client will always connect to same worker server, and socket.io will work as expected, but on multiple processes)

  • socket.io-redis (Run multiple socket.io instances in different processes or servers that can all broadcast and emit events to and from each other.

In the need to share worker processes over different servers in the future i would also need to use nginx as a proxy. If i have understood it correctly?

I have now installed redis-server on my local server but how can i get my current code below to connect to my local redis-server and share everything between several workers?

var https = require("https"), fs = require("fs");
var options = {
    key:    fs.readFileSync('/path/privkey.pem'),
    cert:   fs.readFileSync('/path/cert.pem'),
    ca:     fs.readFileSync('/path/chain.pem')
};
var app = https.createServer(options, function(){

});
var io = require("socket.io")(app);
var all_clients = {};

io.set("transports", ["websocket", "polling"]);

io.on("connection", function(client){

    client.on("chat_message", function(data){
        // handle incoming chat message and emit to other user
    });

    client.on("disconnect", function(){
        // client disconnected
    });    
});

app.listen(8888, function(){
  // listening on port 8888
});

var recursive = function () {
  // echo currently connected sockets
  console.log("Connected sockets: "+io.engine.clientsCount);
  setTimeout(recursive,5000);
}
recursive(); 

Edit: The answer in the link you provided as a duplicate is not functioning in the current version of socket.io (since 2015). Please check the comments in your provided link.

0

There are 0 answers