【问题标题】:socket.io 2.0 get connected clients in a roomsocket.io 2.0 在房间里连接客户端
【发布时间】:2018-01-09 20:07:16
【问题描述】:

如何使用 socket.io 2.0 检索房间中所有连接的客户端


我已经尝试过类似问题的解决方案:https://stackoverflow.com/a/45160538/2189845

var sockets = io.in("room_name")
 Object.keys(sockets.sockets).forEach((item) => {
 console.log("TODO: Item:", sockets.sockets[item].id)            
})

但这会循环所有套接字连接,无论房间如何。所以上面的代码给出了相同的结果:

Object.keys(io.sockets.sockets).forEach((item) => {
    console.log("general socket: Item:", item);
});

【问题讨论】:

    标签: socket.io


    【解决方案1】:

    试试:

    io.sockets.clients('room_name').forEach(function(item) {
        console.log(item.id);//any property of socket you want to print
    });
    

    或者你可以试试:

    var clients = io.sockets.adapter.rooms['room_name'].sockets;
    for (var clientId in clients ) {
    
         //this is the socket of each client in the room.
         var SocketofClient = io.sockets.connected[clientId];
         console.log(SocketofClient.id);
    }
    

    【讨论】:

    • 这些在 2.0 中不再有效。我收到第一个解决方案的“TypeError:fn.bind is not a function”和第二个解决方案的“TypeError: Cannot read property 'sockets' of undefined”。
    【解决方案2】:

    不幸的是,这个答案并不能完全满足 OP 的问题。如果您使用socket.io-redis 管理套接字连接,您可以获得连接的客户端,例如

    io.of('/').adapter.clients((err, clients) => {
      console.log(clients); // an array containing all connected socket ids
    });
    
    io.of('/').adapter.clients(['room1', 'room2'], (err, clients) => {
      console.log(clients); // an array containing socket ids in 'room1' and/or 'room2'
    });
    
    // you can also use
    
    io.in('room3').clients((err, clients) => {
      console.log(clients); // an array containing socket ids in 'room3'
    });
    

    来自:https://github.com/socketio/socket.io-redis#redisadapterclientsroomsarray-fnfunction

    【讨论】:

    • 这行得通,所以我接受了这个作为正确答案。当您只运行 1 个节点服务器时,感觉有点矫枉过正。您需要运行一个额外的 redis 服务器,仅用于获得已连接客户端的列表。希望有一个更简单的解决方案,但我会选择这个。我猜这让我们准备好升级到多个节点服务器。
    • 如何使用套接字 id 跟踪用户信息?可以使用 redis 键值对,但是如果服务器重新启动并且客户端重新连接,则会创建一个新的套接字 id,而旧的套接字 id 会保留在 redis 中,从而导致内存泄漏。
    【解决方案3】:

    检查在 socket.io 2.0 中运行的这段代码

      io.sockets.in(roomID).clients(function(err, clients) {
                                clients.forEach(client => {
                                    let user = io.sockets.connected[client];
                                    console.log("Connected Client ", user.displayName);
                                });
                            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 2012-06-06
      相关资源
      最近更新 更多