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.
Just a few things.
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);
you where missing a closing quote (') in your:
console.log('User joined chat room 1);
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.
to help you out more i would need to see all your code as this does not give me context.
You can create an array object of user collection as
then on server side you can add it as new user when you connect
while displaying the users, you can loop the "users" object
On Client side
For people using socket.IO versions 1.0 or greater the above answer may not work. Please refer the following answer for doing so. Get list of all clients in specific room
Code to update socket object for all clients in a room
Instead of going deep in
socket/io
object , You can use simple and standard way :For more detail DO READ
I just logged all sockets in a room to the console, you can do whatever you like with them...
All the answers above and the one here socket.io get rooms which socket is currently in or here Socket.IO - how do I get a list of connected sockets/clients? were either incorrect or incomplete if you use 2.0.
Without using namespace, following 3 parameters can all get sockets in a specific room.
socket.adapter.rooms;
io.sockets.adapter.rooms;
io.sockets.adapter.sids;// the socket.id array
With namespace (I used "cs" here), io.sockets.adapter.rooms will give a quite confusing result and the result socket.adapter.rooms gives is correct:
/* socket.adapter.rooms give: */
{"/cs#v561bgPlss6ELZIZAAAB":{"sockets":{"/cs#v561bgPlss6ELZIZAAAB":true},"length":1},"a room xxx":{"sockets":{"/cs#v561bgPlss6ELZIZAAAB":true},"length":1}}
/* io.sockets.adapter.rooms give: a sid without namespace*/
{"v561bgPlss6ELZIZAAAB":{"sockets":{"v561bgPlss6ELZIZAAAB":true},"length":1}}
Note: the default room is this: "Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id."
I only tried memory adapter so far, have not tried redis-adapter.