Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 853
franzlorenzon Avatar asked May 13 '13 08: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 I monitor socket.io traffic?

Use Monitor.io to observe connections and replay messages When you add it to your Node. js application, it provides a monitoring interface that you can access remotely by opening a Telnet connection to a particular port. It shows a list of active Socket.io client connections for your application.

What is socket.io connection?

Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection.


2 Answers

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.

like image 54
robertklep Avatar answered Sep 28 '22 05:09

robertklep


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.

like image 20
Ansari Abdullah Avatar answered Sep 28 '22 06:09

Ansari Abdullah