franzlorenzon
franzlorenzon

Reputation: 5943

Get connection status on Socket.io client

I'm using Socket.io, and I'd like to know the status of connection to the server from the client-side.

Something like this:

socket.status // return true if connected, false otherwise

I need this information to give a visual feedback to the user if the connection has dropped or it has disconnected for any reason.

Upvotes: 97

Views: 189952

Answers (6)

Kiran Poojary
Kiran Poojary

Reputation: 233

curl "<the server URL>/socket.io/?EIO=4&transport=polling"

Execute the above curl in command prompt or Postman Output should be look like below for successfull connections

0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}

Upvotes: 0

Na Nonthasen
Na Nonthasen

Reputation: 182

These days, socket.on('connect', ...) is not working for me. I use the below code to check at 1st connecting.

if (socket.connected)
  console.log('socket.io is connected.')

and use this code when reconnected.

socket.on('reconnect', ()=>{
  //Your Code Here
});

Upvotes: 8

Qiulang
Qiulang

Reputation: 12475

@robertklep's answer to check socket.connected is correct except for reconnect event, https://socket.io/docs/client-api/#event-reconnect As the document said it is "Fired upon a successful reconnection." but when you check socket.connected then it is false.

Not sure it is a bug or intentional.

Upvotes: 2

Ansari Abdullah
Ansari Abdullah

Reputation: 91

You can check whether the connection was lost or not by using this function:-

var socket = io( /**connection**/ );
socket.on('disconnect', function(){
//Your Code Here
});

Hope it will help you.

Upvotes: 9

Ilan
Ilan

Reputation: 162

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

Upvotes: 3

robertklep
robertklep

Reputation: 203534

You can check the socket.connected property:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);
});

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

Upvotes: 146

Related Questions