node.js - 如何在socketio-redis管理的socketio进程集群中查找用户socket

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

我是 socketio-redis 适配器的新手。最初我有一个socketio进程,但现在尝试一个socketio集群。

当它是单个进程时,我会维护一个已连接套接字的映射,以通过 userId 查找套接字。当用户 A 发送到房间时,如果用户 B 已连接但尚未进入该房间,则 B 的套接字会被发现并加入该房间。然后A的套接字发送到房间。

我的问题是,如何使用 socketio-redis 来解决这个问题?

下面是一个简化的计划。是否可以在一个 socketio 进程中的连接上将 userId 添加到套接字,然后在不同的进程中通过 userId 查找该套接字?

chatio.on('connect', socket => {
  // add userId to socket obj
  socket.userId = userId
  . . .
  socket.on("message", async (data, ack) => {
    const userId  = data.otherUserId
    const roomId  = data.roomId
    const message = data.message
    const clients = await io.of('/').adapter.clients()

    // a message came in from user A
    // if user B socket is found, B joins same room
    const otherUserSocket = clients.find(socketId => {
      const s = io.of('/').adapter.connected[socketId]
      return (s.userId == userId)
    })

    if (otherUserSocket) {
      otherUserSocket.join(roomId)
      socket.to(roomId).emit("message", { message })
    }
  }
})

有人有实现类似事情的经验吗?

最佳答案

我认为您可以使用 customRequest/customHook 向每个 Node 发送请求以查找具有所需 userId 的套接字:

RedisAdapter#customRequest(data:Object, fn:Function)

然后让它加入房间。

编辑:也许这个例子可以帮助你:

let ns = io.of('/');
ns.on('connection', socket => {
    // add userId to socket obj
    socket.userId = socket.handshake.query.userId
    console.log("New user connected: " + socket.userId);

    socket.on("message", data => {
      ns.adapter.customRequest(data, (err,results) =>{
        if(err){
            console.log('Error : ' + err.message)
        }else{
            console.log(results);
            socket.to(data.roomId).emit("message", data.message)
        }
      }); 
    })
})

ns.adapter.customHook = (data, cb) => {
    let otherUserId  = data.otherUserId
    let roomId  = data.roomId
    let clients = Object.keys(ns.sockets)

    clients.forEach(socketId => {
        if(ns.sockets[socketId].userId === otherUserId){
            ns.sockets[socketId].join(roomId)
            return cb(true)
        }
    });
    return cb(false)
}

关于node.js - 如何在socketio-redis管理的socketio进程集群中查找用户socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58016359/

相关文章:

javascript - 如何通过node_redis创建队列

redis - 如何防止重复图中的数据重复?

swift - 将 AnyObject 转换为特定类

ios - 从 Swift 中的 Socket 获取响应

javascript - 服务器端连接到 socket.io 服务器

node.js - 无法让 Puppeteer 工作和安装

javascript - Node.js express NPM 启动错误,退出状态 8

javascript(node.js) |在回调函数的范围内使用外部参数

javascript - 如何使scrollIntoView()在第一次点击时起作用(Angular 6)?

typescript - socket.io-redis typescript 错误