node.js http.IncomingMessage不会触发'close'事件

时间:2013-11-20 13:26:37

标签: node.js node.js-stream

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。

1 个答案:

答案 0 :(得分:5)

在发送响应之前关闭基础连接时会触发'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