gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:38:54 29 4
gpt4 key购买 nike

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。

最佳答案

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

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

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 !

关于node.js http.IncomingMessage 不触发 'close' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20097255/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com