0

i use web sockets and the onclose method does not get triggert when the server is down.
i tried to close the ws connections manually with progress.exit but it seems this only gets triggert on a clean exit.

is their a way to catch a stopped nodejs app and execute code before the stop?
it should trigger on ctr+c and any other crash/exit.

basicly i want to tell the client when the connection is not alive anymore before he is trying to do something, since onclose does not handel every case, what can i do to check the connection?

the only solution i came up with is to ping the server from time to time.

yellowsir
  • 741
  • 1
  • 9
  • 27
  • 1
    It is normal, although not always wanted, to have a "cleanup limit". Otherwise the server might get stuck in an endless cleanup loop. Hence, you should expect the server's `onclose` method to not always be called. As for process exit cleanup, consider using the `process.on('exit', function() {});` as described [here](http://stackoverflow.com/questions/8510008/express-js-shutdown-hook). – Myst Sep 23 '15 at 12:44

2 Answers2

0

since this is not possible i started sending pings as a workarround:

var pingAnswer = true;
pingInterval = setInterval(function(){
  if(pingAnswer){
    ws.send(JSON.stringify({type:'ping'})); //on the serverside i just send a ping back everytime i recive one.
    pingAnswer = false;
  }else{
     clearInterval(pingInterval);
    //reload page or something
  }
},1000);
ws.onMessage(function(e){
  m = JSON.parse(e.data);
  switch(m.type){
  ....
  case 'ping':
     pingAnswer=true;
  return; 
  }
}

);
yellowsir
  • 741
  • 1
  • 9
  • 27
0

You don't provide a snippet showing how you're defining your on('close',...) handler, but it's possible that you're defining the handler incorrectly.

At the time of this writing, the documentation for websocket.onclose led me to first implement the handler as ws_connection.onclose( () => {...});, but I've found the proper way to be ws_connection.on('close', () => {...} );

Maybe the style used in the ws documentation is some kind of idiom I'm unfamiliar with.

I've tested this with node 6.2.1 and ws 1.1.1. The on.('close',...) callback is triggered on either side (server/client) when the corresponding side is shutdown via Ctrl+c or crashes for whatever reason (for example, for testing, JSON.parse("fail"); or throw new Error('');).

orphen
  • 66
  • 1
  • 5