如何检测客户端从node.js服务器断开连接

我是新的node.js。 如何检测客户端与node.js服务器断开连接。

这是我的代码

var net = require('net'); var http = require('http'); var host = '192.168.1.77'; var port = 12345;// var server = net.createServer(function (stream) { stream.setEncoding('utf8'); stream.on('data', function (data) { var comm = JSON.parse(data); if (comm.action == "Join_Request" && comm.gameId =="game1") // join request getting from client { var reply0 = new Object(); reply0.message = "WaitRoom"; stream.write(JSON.stringify(reply0) + "\0"); } }); stream.on('disconnect', function() { }); stream.on('close', function () { console.log("Close"); }); stream.on('error', function () { console.log("Error"); }); }); server.listen(port,host); 

如何知道客户端的networking断开。

检测“死锁”的最好方法是定期发送应用程序级别的ping / keepalive消息。 这个消息看起来像取决于你使用通过套接字进行通信的协议。 然后,只有在使用定时器或其他方式检查在将ping / keepalive消息发送到客户端之后的某个时间段内是否收到“ping响应”的问题。

在半相关说明中,它看起来像是使用JSON消息进行通信,但是对于每个data事件,您都假设一个完整的JSONstring,这是一个糟糕的假设。 尝试使用分隔符(换行符在这类事情中很常见,而且它使debugging通信更加人性化)。

这里是一个简单的例子,如何实现这一点:

 var PING_TIMEOUT = 5000, // how long to wait for client to respond WAIT_TIMEOUT = 5000; // duration of "silence" from client until a ping is sent var server = net.createServer(function(stream) { stream.setEncoding('utf8'); var buffer = '', pingTimeout, waitTimeout; function send(obj) { stream.write(JSON.stringify(obj) + '\n'); } stream.on('data', function(data) { // stop our timers if we've gotten any kind of data // from the client, whether it's a ping response or // not, we know their connection is still good. clearTimeout(waitTimeout); clearTimeout(pingTimeout); buffer += data; var idx; // because `data` can be a chunk of any size, we could // have multiple messages in our buffer, so we check // for that here ... while (~(idx = buffer.indexOf('\n'))) { try { var comm = JSON.parse(buffer.substring(0, idx)); // join request getting from client if (comm.action === "Join_Request" && comm.gameId === "game1") { send({ message: 'WaitRoom' }); } } catch (ex) { // some error occurred, probably from trying to parse invalid JSON } // update our buffer buffer = buffer.substring(idx + 1); } // we wait for more data, if we don't see anything in // WAIT_TIMEOUT milliseconds, we send a ping message waitTimeout = setTimeout(function() { send({ message: 'Ping' }); // we sent a ping, now we wait for a ping response pingTimeout = setTimeout(function() { // if we've gotten here, we are assuming the // connection is dead because the client did not // at least respond to our ping message stream.destroy(); // or stream.end(); }, PING_TIMEOUT); }, WAIT_TIMEOUT); }); // other event handlers and logic ... }); 

你也可以只有一个间隔,而不是两个定时器,它们检查当前时间戳上的“最后一个数据收到”时间戳,如果它超过了一段时间,我们最近发送了一个ping消息,那么你认为套接字/连接已经死了。 你也可以发送多个ping消息,如果ping消息发送后没有收到响应,closures连接(这基本上是OpenSSH的)。

有很多方法可以去做。 但是,您也可以考虑在客户端执行相同的操作,以便您知道服务器也不会丢失连接。