Zander17
Zander17

Reputation: 1954

Listing all the clients connected to a room in Socket.io version > 1

After the io.sockets.clients() method has been depreciated from the later versions of Socket.io, and after my research couldn't find any documentation on the socket.io offical web.

Morever, it gives the type error for clients() method as below:

TypeError: undefined is not a function

Has anyone figured out how to list all the connected clients in a room with the later versions of Socket.io?

Upvotes: 13

Views: 13115

Answers (2)

KIA
KIA

Reputation: 192

In Socket.IO 1.4

To get the array of All connected Users :

// io.sockets.connected returns an Object with socketId as its key 

var allConnectedClients = Object.keys(io.sockets.connected);// This will return the array of SockeId of all the connected clients

To get the Count of all clients :

var clientsCount = io.engine.clientsCount ; // This will return the count of connected clients

Upvotes: -2

Oleg
Oleg

Reputation: 23268

To get socket IDs of the clients connected to a room use this code:

var namespace = '/';
var roomName = 'my_room_name';
for (var socketId in io.nsps[namespace].adapter.rooms[roomName]) {
    console.log(socketId);
}

Edit:

To get socket by socket ID you may try this:

var socket = io.sockets.connected[socketId];

Upvotes: 27

Related Questions