2013-11-20 90 views
3

http.IncomingMessage何時觸發其「關閉」事件?node.js http.IncomingMessage不會觸發「關閉」事件

根據documentation它應該發生在底部連接關閉時。但是,它絕不會爲下面的示例代碼(我確信它不會被保活造成的):

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。

+0

我不確定,但在完成之前試圖中止請求呢?原諒我,如果我說牛屎 – gustavohenke

+0

你是對的,也許'關閉'被解僱,當底層連接在響應被髮送前關閉? – roediger

+1

試試看,延遲幾秒鐘,看看會發生什麼 – gustavohenke

回答

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