3

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?

Community
  • 1
  • 1
alevkon
  • 327
  • 4
  • 13

1 Answers1

1

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.

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106
  • 1
    I described the way I make and break a connection - I simply open the page with nodejs URL in the browser and then click Stop button. It's very common way, isn't it? I also know that the most of the online chat application (like chats in GMail) can understand that the user goes offline just after he closes the long-poll connection. How do they do it if I use the same OS and browser as in my example? – alevkon Oct 12 '11 at 09:20
  • The only way to know what the browser does when you click the stop button is to read the browser source code, or use Wireshark and watch the network traffic. Much easier to just do some research on TCP programming best practices. Stuff like this http://msdn.microsoft.com/en-us/library/windows/desktop/ms738547(v=vs.85).aspx and this http://fixunix.com/unix/526177-how-fast-close-socket.html – Michael Dillon Oct 13 '11 at 07:25