ws: onclose not called if a client disconnects due to network failure

I am listening to the close event from a client on a node server using websocket.on('close', function close() { } );

However, the callback is not being fired if a client gets disconnected due to network failure.

Is there any way to detect dead connections on the server side ?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 10
  • Comments: 15 (1 by maintainers)

Most upvoted comments

I’ve got the same problem with detecting connections experiencing network errors. I’ve tried setting keepAlive, as pointed here, but close event still fired only 10 s after network got down. Finally, I figured out how to use Websocket ping-pong mechanism:

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ port: 4444 });

var PONG_TIMEOUT = 1500; //client has 1.5s to respond with pong

wss.on('connection', function connection(ws) {
    var lastPongReceived = Date.now();
    ws._socket.on('data', function(data) {
        if (data[0] == 0x8a) { //opcode of pong response
            lastPongReceived = Date.now();
        }
    });

    var x = setInterval(function() {
        if (Date.now() - lastPongReceived > PONG_TIMEOUT) {
            console.log('pong timeout elapsed');
            //...code to run if connection unavailable
            clearInterval(x);
            ws._socket.destroy(); //ws.close() won't raise 'close' event, because close message 
                                   //cannot be delivered to client      
        }
        if (ws.readyState === 1) {
            ws.ping('.', false);
        } 
    }, 1000);

    ws.on('close', function() {
        console.log('connection closed');
    })
});

This is my implementation: https://github.com/urosjarc/websocketRest.js It’s used in production for 1 year +2000 mobile devices connected which are switching connections (wifi, 3G) all the time. We were having many problems with duplicats but now this lib is running 1 year without error. This is the company that use this lib: http://facilityforhotels.com/

A possible way to handle this issue is illustrated here: https://github.com/websockets/ws#how-to-detect-and-close-broken-connections. Closing, feel free to continue discussing on the closed thread.