1

Hello I'm trying to loop through all connected sockets and check if they have the session data (userid) I'm looking for. Here's my code (doesn't work):

var clients = io.sockets.clients();
console.log(clients);

for(i = 0; i < clients.length; i++) {
    if(clients[i].handshake.session.userid == userid) {
        clients[i].emit(event, data);
    }
}

My question is how I could find an array of sockets since io.sockets.clients() doesn't seem to return an array with the socket objects.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Johnny Code
  • 39
  • 2
  • 6

2 Answers2

2

This should help you.

var sockets = io.sockets.sockets;
for(var socketId in sockets) {
          var s = sockets[socketId]; 
}
zdimon77
  • 131
  • 10
0

socket.io@2.3.0

io.sockets.sockets is an object where a key is a socketId and value is reference to the socket object.

Object.keys(io.sockets.sockets).forEach((socketId) => {
  const socket = io.sockets.sockets[socketId];
})
saro928
  • 3
  • 3
Ramit Mittal
  • 483
  • 3
  • 12