如何使用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);
});
答案 0 :(得分:1)
不幸的是,这个答案并不能完全满足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 :(得分:0)
尝试:
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)
检查在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);
});
});