【发布时间】:2016-01-11 14:35:55
【问题描述】:
我无法弄清楚我遇到的一个问题。 我在我的 Node.JS 服务器上使用 Net 模块,用于监听客户端连接。
客户端确实正确连接到服务器,并且连接仍然可用于读取/写入数据。到现在为止还挺好。但是当客户端意外断开连接时(编辑。当互联网在客户端断开时)我想触发事件服务器端。
在 socket.io 中,它会通过 'disconnect' 事件来完成,但对于 Net 模块,这个事件似乎不存在。怎么可能?
我在 Google/StackOverflow 和 Net 文档 (https://nodejs.org/api/net.html) 上进行了搜索,但找不到任何有用的东西。如果我做错了什么,我很抱歉。
这是我得到的代码 sn-p:
var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.wildcard = false;//Connection must be initialised with a configuration stored in the database
connection.bidirectional = true;//When piped this connection will be configured as bidirectional
connection.setKeepAlive(true, 500);
connection.setTimeout(3000);
connection.on('close', function (){
console.log('Socket is closed');
});
connection.on('error', function (err) {
console.log('An error happened in connection' + err.stack);
});
connection.on('end', function () {
console.log('Socket did disconnect');
});
connection.on('timeout', function () {
console.log('Socket did timeout');
connection.end();
});
connection.on('data', function (data) {
//Handling incoming data
});
});
serverUmrs.listen(40000, function () {
console.log('server is listening');
});
当我断开客户端(通过拔出 UTP 电缆)时,所有事件(关闭、结束、错误、超时)都不会触发。
提前致谢!
编辑: 我确实在上面的代码中添加了一个超时事件,但唯一发生的事情是,每次客户端再次连接时,套接字都会在 3 秒后超时。 KeepAlive 还不足以使套接字不空闲吗?如何在没有太多开销的情况下使套接字不空闲。有可能同时存在超过 10,000 个连接,只要它们连接(即响应 keepalive 消息)就必须保持活动状态。
【问题讨论】:
-
拔出UTP线后,客户端3秒后是否再次连接?