List of connected clients username using socket io


Question

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 wich 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
    }
});
1
35
5/23/2017 12:10:44 PM

Accepted Answer

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.

42
5/23/2017 11:55:09 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon