Sharing sockets over separate nodeJS instances

走远了吗. 提交于 2019-12-11 13:22:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28050539/sharing-sockets-over-separate-nodejs-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!