List of connected clients username using socket io

kimpettersen picture kimpettersen · Jan 9, 2012 · Viewed 72.6k times · Source

I've made a chat client with different chat rooms in NodeJS, socketIO and Express. I am trying to display an updated list over connected users for each room.

Is there a way to connect a username to an object so I could see all the usernames when I do:

var users = io.sockets.clients('room')

and then do something like this:

users[0].username

In what other ways can I do this?

Solved:
This is sort of a duplicate, but the solution is not written out very clearly anywhere so I'd thought I write it down here. This is the solution of the post by Andy Hin which was answered by mak. And also the comments in this post.

Just to make things a bit clearer. If you want to store anything on a socket object you can do this:

socket.set('nickname', 'Guest');    

sockets also has a get method, so if you want all of the users do:

for (var socketId in io.sockets.sockets) {
    io.sockets.sockets[socketId].get('nickname', function(err, nickname) {
        console.log(nickname);
    });
}

As alessioalex pointed out, the API might change and it is safer to keep track of user by yourself. You can do so this by using the socket id on disconnect.

io.sockets.on('connection', function (socket) { 
    socket.on('disconnect', function() { 
        console.log(socket.id + ' disconnected');
        //remove user from db
    }
});

Answer

alessioalex picture alessioalex · Jan 9, 2012

There are similar questions that will help you with this:

Socket.IO - how do I get a list of connected sockets/clients?

Create a list of Connected Clients using socket.io

My advice is to keep track yourself of the list of connected clients, because you never know when the internal API of Socket.IO may change. So on each connect add the client to an array (or to the database) and on each disconnect remove him.