nikitz
nikitz

Reputation: 1091

Sharing sockets over separate nodeJS instances

I'm making chat application with multiple chat servers(nodeJS) and one redis server which should help grouping all nodeJS instances. Well I have this:

var io = require('socket.io').listen(3000);

// Create a Redis client
var redis  = require('redis');
client = redis.createClient(6379, '54.154.149.***', {});

// Check if redis is running
var redisIsReady = false;
client.on('error', function(err) {
    redisIsReady = false;
    console.log('redis is not running');
    console.log(err);
});
client.on('ready', function() {
    redisIsReady = true;
    console.log('redis is running');
});


io.sockets.on('connection', function(socket){
    socket.on('new user', function(data){
            client.set('user:' + data, socket.id);
    })

    socket.on('send message', function(data){
        client.get('user:' + data['id'], function (err, socketId) {
            io.sockets.connected[socketId].emit('new message',data['msg']);
        });
    })

    socket.on('disconnect', function(data){

    });
});

The redis is working perfectly and if I have two users on the same server they can chat. But if they are on different servers they cannot because the sockets aren't shared between the servers. How can I resolve this? I checked about pub/sub on redis and I'm sure that's the answer but I didn't manage to implement it.

Upvotes: 1

Views: 1506

Answers (1)

mscdex
mscdex

Reputation: 106746

The Socket.IO docs have a section about doing sticky sessions and distributing messages. The quick answer though is to use a module like socket.io-redis.

Upvotes: 3

Related Questions