Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
franzlorenzon Avatar asked May 23 '13 12:05

franzlorenzon


People also ask

How do I know if socket IO client is connected?

You can check the socket. connected property: var socket = io. connect(); console.

How do you get socket ID socket IO?

socket.id can be obtained after 'connect' event. Note, the socket.id on the server is not made available to the client, so if you want the id from the server, then you can send it to the client yourself in a message.

What is socket ID in socket IO?

Socket#id​Each new connection is assigned a random 20-characters identifier. This identifier is synced with the value on the client-side. io. on("connection", (socket) => { console.


2 Answers

As of today, Feb, 2015, none of the methods listed here work on the current version of Socket.io (1.1.0). So on this version, this is how it works for me :

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

the io.sockets.server.eio.clients is an array containing a list of all the live socket id's. So use the code in the if statement to check if a particular socket ID is in this list.

like image 52
Karan Kapoor Avatar answered Nov 03 '22 02:11

Karan Kapoor


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

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

Also you can set timeout

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

This checks if socket connected in 5 seconds.

like image 40
notgiorgi Avatar answered Nov 03 '22 01:11

notgiorgi