yellowsir yellowsir - 3 months ago 15
Node.js Question

ws.onclose event does not get called on nodejs exit

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.

Answer

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; 
  }
}

);