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

I am new to node.js and javascript. I am using socket.io and trying to list the sockets connected in this room. When the socket is connected, I give it an alias:

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

With this code, I can get the socket id:

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

But how can I access the alias property in this loop? Trying socketID.nicknameor socketID[nickname]will cause an error. Nick is not determined.

+4
source share
1 answer

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

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

nspshas the properties adapterand connected.

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

+1
source

Source: https://habr.com/ru/post/1688676/


All Articles