Socket.IO: Detect disconnected sockets

时间:2015-08-07 02:23:28

标签: javascript node.js socket.io

I have a socket.io server/client. When a client safely disconnects, on the server side, the line

socket.on('disconnect', function() {

});

is called.

However, if the client server crashes, then socket.on('disconnect') is never called; I know this because I recursively print out wss.sockets.connected.length and the number does not decrease.

How can I check that such a crash has happened on the server?

2 个答案:

答案 0 :(得分:1)

您应该最终收到disconnect事件,因为socket.io具有心跳机制。我不认为有任何其他方法可以检测到客户端崩溃。确实需要一些时间。

心跳已在此处得到解释:

Advantage/disadvantage of using socketio heartbeats

答案 1 :(得分:0)

当服务器调用disconnect()时,断开处理程序的原因是:io server disconnect。当服务器停止时,原因是:运输关闭。 因此,您可以通过添加条件来检查:

socket.on('disconnect', function(reason) {
  if (reason === 'transport close'){
    console.log('Server Crashed');
  } 
});