Search code examples
javascriptnode.jssocket.io

Socket IO Rooms: Get list of clients in specific room


I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.

This where I'm at:

socket.set('nickname', "Earl");  
socket.join('chatroom1');
console.log('User joined chat room 1);
                
var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
   console.log('Username: ' + roster[i]);   
}

Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.


Solution

  • 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.