node.js http.IncomingMessage不会触发“关闭"事件 [英] node.js http.IncomingMessage does not fire 'close' event

查看:149
本文介绍了node.js http.IncomingMessage不会触发“关闭"事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

According to the documentation it should occur when the underlaying connection was closed. However, it is never called for the following example code (I made sure it is not caused by 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.

I'm using node.js v0.10.22.

推荐答案

在发送响应之前关闭基础连接时,将触发"close"事件.

The 'close' event is fired, when the underlying connection was closed before the response was sent.

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

Can be tested using the following server code and aborting the request midway through.

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不会触发“关闭"事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆