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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With