Socket.io: check connection status with socket id

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

Something like that:

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 any way to do this?

+4
source share
5 answers

For versions above 1.0, check Karan Kapoor's answer. For older versions, you can access any connected socket using io.sockets.sockets[a_socket_id] , so if you set the status variable for it, io.sockets.sockets[a_socket_id].status will work.

First you need to check if the socket really exists, and it can also be used to check for 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"); } 
+12
source

To date, February 2015, none of the methods listed here work in the current version of Socket.io (1.1.0). So, in this version, this is how it works for me:

 var socketList = io.sockets.server.eio.clients; if (socketList[user.socketid] === undefined){ 

io.sockets.server.eio.clients is an array containing a list of all live socket identifiers. Therefore, use the code in the if statement to check if a specific socket identifier is specified in this list.

+5
source
 if (io.sockets.connected[socketID]) { // do what you want } 
+2
source

Socket.io> = 1.0, as Riwels will answer, you must first check if a socket exists

 if(io.sockets.connected[a_socket_id]!=undefined){ console.log(io.sockets.connected[a_socket_id].connected); //or disconected property }else{ console.log("Socket not connected"); } 
+1
source

In newer versions, you can check the socket.connected property.

 var socket = io(myEndpoint) console.log(socket.connected) // logs true or false 

You can also set a timeout.

 setTimeout(function() { if(! socket.connected) { throw new Error('some error') } }, 5000) 

This checks if the socket is connected after 5 seconds.

0
source

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


All Articles