【问题标题】:node.js http.IncomingMessage does not fire 'close' eventnode.js http.IncomingMessage 不会触发“关闭”事件
【发布时间】:2013-11-20 13:26:36
【问题描述】:

http.IncomingMessage 何时触发其“关闭”事件?

根据documentation,它应该在底层连接关闭时发生。但是,以下示例代码从未调用它(我确保它不是由 keep-alive 引起的):

var http = require('http'),
    fs = require('fs');

var server = http.createServer(function(req, res) {
    res.shouldKeepAlive = false;
    req.on("end", function() {
        console.log("request end");
    });
    req.on("close", function() {
        console.log("request close");    // Never called
    });
    res.end("Close connection");
});
server.listen(5555);

我正在使用 node.js v0.10.22。

【问题讨论】:

  • 我不确定,但是如果在请求完成之前尝试中止请求呢?如果我在说废话,请原谅我
  • 你是对的,当底层连接在发送响应之前关闭时,可能会触发'close'?
  • 试试看,延迟几秒看看会发生什么
  • 你是对的!谢谢!
  • @gustavohenke 这是一个很好的问题,因为文档nodejs.org/api/http.html#http_event_close_2 没有明确说明。这个问题和答案有帮助。无论如何触发关闭事件会更有意义,我经常将底层连接打开以提高效率。更合适的术语是“中止”事件。

标签: node.js node.js-stream


【解决方案1】:

当底层连接在响应发送之前关闭时,会触发 'close' 事件。

可以使用以下服务器代码进行测试,并在中途中止请求。

var http = require('http'),
    fs = require('fs');

var server = http.createServer(function(req, res) {
    res.shouldKeepAlive = false;
    req.on("end", function() {
        console.log("request end");
    });
    req.on("close", function() {
        console.log("request close");    // Called, when connection closed before response sent
    });

    setTimeout(function () {
        res.end("Close connection");
    }, 5000); // Wait some time to allow user abort
});
server.listen(5555);

感谢gustavohenke

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多