franzlorenzon franzlorenzon - 2 months ago 42
Node.js Question

Socket.io: check the status of a connection with the socket id

I have a socket id of a connection. Can I get the status of that connection, inside the function handler of another one?

Something like this:

io.sockets.on('connection', function(socket) {
/* having the socket id of *another* connection, I can
* check its status here.
*/
io.sockets[other_socket_id].status
}


Is there a way to do so?

Answer

For versions higher than 1.0, check Karan Kapoor answer. For older versions, you can access any connected socket with io.sockets.sockets[a_socket_id], so if you've set a status variable on it, io.sockets.sockets[a_socket_id].status will work.

First you should check if the socket really exists, and it can also be used to check connected/disconnected statuses.

if(io.sockets.sockets[a_socket_id]!=undefined){
  console.log(io.sockets.sockets[a_socket_id]); 
}else{
  console.log("Socket not connected");
}