http - request.close 事件不会在 node.js 服务器中触发

标签 http node.js long-polling

我正在开发使用 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");

我无法让它正常工作:

  1. 我在浏览器中打开与 node.js 服务器连接的特定 URL

  2. 之后立即单击“停止”按钮。

  3. 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/

相关文章:

http - http Keep-Alive不就解决了long-polling解决的问题吗?

http - 保持事件标题说明

angular - API的HTTP错误消息未在Angular组件中显示

wcf - 如何在 WCF 客户端服务代理上设置 HTTP 代理 (WebProxy)?

node.js - 如何在 Mongoose 中间件中发出事件?

node.js - 用 CoffeeScript jsx 开 Jest ?

php - file_get_contents 返回 HTTP/1.1 301 永久移动

node.js - 端口*和*路径上的 NodeJS 套接字?

PHP - 长轮询通知(PHP 标志还是其他方式?)

php - Nginx + PHP : stop process at canceled request