Reputation: 890
How can you retrieve all the connected clients in a room using socket.io 2.0
I already tried the solution in a similar question: 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)
})
But this loops over all socket connections, regardless of the room. So the code above gives the same result as:
Object.keys(io.sockets.sockets).forEach((item) => {
console.log("general socket: Item:", item);
});
Upvotes: 2
Views: 5824
Reputation: 1194
Check this code which is run in 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);
});
});
Upvotes: 0
Reputation: 5213
Unfortunately, this answer doesn't completely satisfy OPs question. If you are using socket.io-redis
to manage socket connections you can get connected clients like
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'
});
this is from : https://github.com/socketio/socket.io-redis#redisadapterclientsroomsarray-fnfunction
Upvotes: 2
Reputation: 3576
Try:
io.sockets.clients('room_name').forEach(function(item) {
console.log(item.id);//any property of socket you want to print
});
Or you could try:
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);
}
Upvotes: 0