简体   繁体   English

Socket.IO:检测断开的套接字

[英]Socket.IO: Detect disconnected sockets

I have a socket.io server/client. 我有一个socket.io服务器/客户端。 When a client safely disconnects, on the server side, the line client安全断开连接时,在服务器端,线路

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

});

is called. 叫做。

However, if the client server crashes, then socket.on('disconnect') is never called; 但是,如果客户端服务器崩溃,则永远不会调用socket.on('disconnect') I know this because I recursively print out wss.sockets.connected.length and the number does not decrease. 我知道这一点是因为我递归地打印出wss.sockets.connected.length并且数量不会减少。

How can I check that such a crash has happened on the server? 如何检查服务器上是否发生了此类崩溃?

You should eventually receive the disconnect event, because socket.io has a heartbeat mechanism. 您最终应该收到断开事件,因为socket.io具有心跳机制。 I don't think there is any other way to detect a client crash. 我认为没有其他方法可以检测到客户端崩溃。 It does take some time though. 确实需要一些时间。

Heartbeat has been explained well here: 心跳在这里已得到很好的解释:

Advantage/disadvantage of using socketio heartbeats 使用socketio心跳的优点/缺点

When server calls disconnect(), the reason given to disconnect handler is: io server disconnect. 当服务器调用disconnect()时,给出断开连接处理程序的原因是:io服务器断开连接。 And when server stops, the reason is: transport close. 而当服务器停止时,原因是:传输关闭。 So you can check this by adding a condition: 因此,您可以通过添加条件来进行检查:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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