开发者

request.close event doesn't fire in node.js server

开发者 https://www.devze.com 2023-04-12 15:31 出处:网络
I\'m working on the long-poll application which uses node.js as a server. The particular task is to immediately learn then the user goes offline. So, I have to listen for the request.close event, righ

I'm working on the long-poll application which uses node.js as a server. The particular task is to immediately learn then the user goes offline. So, I have to listen for the request.close event, right?

I copied following piece of code from the How to check if connection was aborted in node.js server

var http = require("http"),
    util = require("util");

var httpServer = http.createServer(function(req, res) {
    util.log("new request...");

    // notify me when client connection is lost
    req.on("close", function(err) {
        util.log("request closed...");
    });

    // wait with response for 15 seconds
    setTimeout(function() {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write("response");开发者_运维知识库
        res.end();

        util.log("response sent...");
    }, 15000);
});
httpServer.listen(8888, "127.0.0.1");
util.log("Running on 8888");

I can't make it working properly:

  1. I open in the browser specific URL connected with the node.js server

  2. Immediately after that click the "Stop" button.

  3. Node.js waits for 15 seconds as if the connection was still alive, and then logs "response sent".

I turned off nginx to prevent any problems, the result is the same. I tried to listen the req.connection.on("close") event also, the result is the same again. The nodejs version is 0.4.12.

What could be wrong?


First of all, you twice mentioned an onclose event and then posted code that listens for a close event. Some people will just skip your question when they see stuff like that.

Secondly, TCP connections are something that the OS manages on behalf of applications. Depending on how you make and break a connection, it is entirely possible for a TCP connection to linger for several minutes after you think that you broke it. Do some research on TCP, socket and linger.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号