我正在开发使用 node.js 作为服务器的长轮询应用程序。特定任务是立即学习,然后用户下线。所以,我必须监听 request.close 事件,对吗?
我从 How to check if connection was aborted in node.js server 复制了以下代码
var http = require("http"),
util = require("util");
var httpServer = http.createServer(function(req, res) {
util.log("new request...");
// notify me when client connection is lost
req.on("close", function(err) {
util.log("request closed...");
});
// wait with response for 15 seconds
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("response");
res.end();
util.log("response sent...");
}, 15000);
});
httpServer.listen(8888, "127.0.0.1");
util.log("Running on 8888");
我无法让它正常工作:
我在浏览器中打开与 node.js 服务器连接的特定 URL
之后立即单击“停止”按钮。
Node.js 等待 15 秒,就好像连接仍然存在一样, 然后记录“已发送响应”。
为了防止出现问题,我关闭了nginx,结果是一样的。我也试着听 req.connection.on("close") 事件,结果还是一样。 nodejs版本是0.4.12。
有什么问题吗?
最佳答案
首先,您两次提到了 onclose
事件,然后发布了监听 close
事件的代码。有些人在看到类似内容时会直接跳过您的问题。
其次,TCP 连接是操作系统代表应用程序管理的东西。根据您建立和断开连接的方式,TCP 连接完全有可能在您认为断开连接后还停留几分钟。对 TCP、socket 和 linger 做一些研究。
关于http - request.close 事件不会在 node.js 服务器中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735818/