【问题标题】:socket.io-redis module not working across serverssocket.io-redis 模块不能跨服务器工作
【发布时间】:2017-12-28 05:19:48
【问题描述】:

大家好,我正在尝试按照socket.io-redis 文档实现 socket.io-redis 模块。将消息从一个客户端广播到同一服务器上的另一个客户端时,它工作正常。但是当我运行两台相同的服务器时,一台在 80 端口,一台在 81 端口,并尝试在客户端 A(连接到端口 80)和客户端 B(连接到端口 81)之间广播消息,没有消息通过。这是我的代码:

const client = require('redis').createClient()
const io = require('socket.io')(server)
const redis = require('socket.io-redis')
io.adapter(redis({ host: 'localhost', port: 6379 }))

io.on('connection', function(socket) {
      socket.on('initializeSocket', function(data) {
                //Assign socket id to client id lookup value
                var clientID = JSON.parse(data).clientID

                client.set(clientID, socket.id)
                console.log("%s client ID redis lookup set to:", clientID)
                console.log(socket.id)
      })

      socket.on('personalMessage-client', function(data) {

                ...

                client.get(facebookID, function(err, socketID) {
                   if(socketID) {
                   console.log('broadcasting to %s', socketID)
                   socket.broadcast.to(socketID).emit('personalMessage-server', message)
                   }
                })
      })
})

当一个 socket 连接初始化时,客户端的用户 ID 被设置为一个键值对到它在 redis 中的相应 socket.id,并通过以下方式检索:

client.get(facebookID, function(err, socketID) {
                   if(socketID) {
                   console.log('broadcasting to %s', socketID)
                   socket.broadcast.to(socketID).emit('personalMessage-server', message)
                   }
                })

redis-cli monitor表示消息实际上正在发布,据我了解,如果两个websocket服务器都连接到同一个redis服务器,websocket消息应该可以在不同地址的服务器之间传递。

但是,当在不同端口上使用两个相同的服务器时,客户端 A 没有收到来自客户端 B 的消息。客户端A只有连接到与客户端B相同端口的服务器时才能接收消息。

如果有人能提供帮助,将不胜感激,据我所知,我使用的 socket.io-redis 适配器模块完全错误。

【问题讨论】:

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


    【解决方案1】:

    尝试传入subClientpubClient,这对我来说很好。

    var redisAdapter = require('socket.io-redis');
    var redis = require('redis');
    var pub = redis.createClient('6379', '127.0.0.1');
    var sub = redis.createClient('6379', '127.0.0.1');
    io.adapter(redisAdapter({
        key: 'adapterKey',
        pubClient: pub,
        subClient: sub,
    }));
    

    还看您发布的屏幕截图,端口号似乎在 62000+ 范围内,这是您的 redis 端口吗?您正在为 socket.io-redis 模块发送 6379(默认端口)。

    【讨论】:

    • 它似乎对我不起作用。您能否发布适合您的 socket.emit 或 socket.broadcast 代码?另外我相信这些端口号只是自动创建的发布/订阅通道的端口,但我的 redis 服务器运行在 6379 上。
    猜你喜欢
    • 2017-11-14
    • 2016-09-09
    • 2014-09-18
    • 1970-01-01
    • 2014-03-13
    • 2017-12-11
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    相关资源
    最近更新 更多