Socket IO Rooms: Get list of clients in specific room

Instead of going deep in socket/io object , You can use simple and standard way :

io.in(room_name).clients((err , clients) => {
    // clients will be array of socket ids , currently available in given room
});

For more detail DO READ


In socket.IO 3.x

New to version 3.x is that connected is renamed to sockets and is now an ES6 Map on namespaces. On rooms sockets is an ES6 Set of client ids.

//this is an ES6 Set of all client ids in the room
const clients = io.sockets.adapter.rooms.get('Room Name');

//to get the number of clients in this room
const numClients = clients ? clients.size : 0;

//to just emit the same event to all members of a room
io.to('Room Name').emit('new event', 'Updates');

for (const clientId of clients ) {

     //this is the socket of each client in the room.
     const clientSocket = io.sockets.sockets.get(clientId);

     //you can do whatever you need with this
     clientSocket.leave('Other Room')

}

In socket.IO 1.x through 2.x

Please refer the following answer: Get list of all clients in specific room. Replicated below with some modifications:

const clients = io.sockets.adapter.rooms['Room Name'].sockets;   

//to get the number of clients in this room
const numClients = clients ? Object.keys(clients).length : 0;

//to just emit the same event to all members of a room
io.to('Room Name').emit('new event', 'Updates');

for (const clientId in clients ) {

     //this is the socket of each client in the room.
     const clientSocket = io.sockets.connected[clientId];

     //you can do whatever you need with this
     clientSocket.leave('Other Room')
}

Just a few things.

  1. when you have the socket you can then set the properties like: socket.nickname = 'Earl'; later to use the save property for example in a console log: console.log(socket.nickname);

  2. you where missing a closing quote (') in your:

    console.log('User joined chat room 1);

  3. Im not entirely sure about your loop.

Below is the amended code should help you out a bit, also be aware the loop i am using below is asynchronous and this may effect how you handle data transfers.

socket.nickname = 'Earl';
socket.join('chatroom1');

console.log('User joined chat room 1');
    
var roster = io.sockets.clients('chatroom1');
        
roster.forEach(function(client) {
    console.log('Username: ' + client.nickname);
});

to help you out more i would need to see all your code as this does not give me context.