Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io how to list sockets in a room by nickname

I'm new to node.js and javascript. I'm using socket.io and trying to list sockets connected in a given room. When a socket connects I give it a nickname:

io.use(function (socket, next) {
  var handshakeUserid = socket.request._query.userid;
  socket.nickname = handshakeUserid;
  next();
});

With this code I can get the id's of the sockets:

 for (socketID in io.nsps['/'].adapter.rooms[room_name].sockets) {
   console.log(socketID);
 }

But how can I access the nickname property in this loop? Trying socketID.nickname, or socketID[nickname] will trow an error nickname is not define.

like image 898
Adry Avatar asked Oct 28 '22 23:10

Adry


1 Answers

I did some debugging and you can access your field by using:

 for (socketID in io.nsps['/'].adapter.rooms[room_name].sockets) {
   const nickname = io.nsps['/'].connected[socketID].nickname;
   // do stuff with nickname
 }

nsps object has the adapter and connected properties.

Connected has a list of all the socket.id and the data that you decorated in the middleware.

like image 106
Alexandru Olaru Avatar answered Nov 15 '22 06:11

Alexandru Olaru