3

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

根据文档,它应该在底层连接关闭时发生。但是,以下示例代码永远不会调用它(我确保它不是由保持活动引起的):

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。

4

1 回答 1

6

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

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

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);

谢古斯塔沃亨克

于 2013-11-22T14:47:39.800 回答