简体   繁体   中英

Detect internet disconnection via socket

Currently I'm using node.js server which has TCP socket connection(using socket.io ) using this I'm showing real-time data via browser.

Consider a scenario, I have logged in to my application and all real-time is shown via web browser. Now all of a sudden the network got disconnected. At that I would like to show a message saying "Expired" when the client-side socket emits the disconnect event.

socket.on('disconnect', function () {
            console.log("Disconnected from the server");
            alert("disconnect");
        });

Now my problem: the above disconnect event is emitted after 60 seconds; In-between when user tries to update, it will not work and this will create a bad impression for us.

How to overcome this situation and how to emit the disconnect event all of a sudden when network got disconnected?

You have to understand heartbeat interval and heartbeat timeout . Earlier is the time when server emits a heartbeat each 25 seconds (by default). And later is timeout for server to keep that specific client in memory. If client receives the heartbeat within heartbeat timeout (60 seconds by default) it tells the server that I'm alive. If client doesn't receive a heartbeat from server within this timeout then server flushes that client out of memory and disconnect event is fired automatically on client side. This timeout is set when client connects to server. So you can set these properties in your Node.js server like this:

var socket = require('socket.io').listen(80,{
  'heartbeat interval': 5,
  'heartbeat timeout' : 10
});

Now server will emit heartbeat every 5 seconds and if client doesn't receive a heartbeat in 10 seconds, disconnect event will be fired. But remember that heartbeat interval should be less than heartbeat timeout. Hope this will work!

This is my solution

var io = require('socket.io')
  .listen(server, {'pingTimeout':4000, 'pingInterval':2000});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM