【问题标题】:Sharing sockets over separate nodeJS instances通过单独的 nodeJS 实例共享套接字
【发布时间】:2015-03-18 23:42:37
【问题描述】:

我正在使用多个聊天服务器(nodeJS)和一个 redis 服务器制作聊天应用程序,这应该有助于对所有 nodeJS 实例进行分组。好吧,我有这个:

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){

    });
});

redis 运行良好,如果我在同一台服务器上有两个用户,他们可以聊天。但是,如果它们在不同的服务器上,则它们不能,因为套接字不在服务器之间共享。我该如何解决这个问题?我检查了 redis 上的 pub/sub,我确定这就是答案,但我没有设法实现它。

【问题讨论】:

  • 注意:在使用共享套接字时,我在 socket.io 中遇到过严重的内存泄漏!

标签: node.js sockets redis socket.io scalability


【解决方案1】:

Socket.IO 文档有一个关于doing sticky sessions and distributing messages 的部分。快速的答案是使用像 socket.io-redis 这样的模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多