Detecting close of client connect in node.js

Tag: node.js Author: wo10nimaa Date: 2010-10-01

I am using node.js for long held connections. I want to know how I can detect when the client connection closes (maybe when the user closes the tab). How do I specify a callback for that?

Other Answer1

Answering my own question - You can detect close of client connection by doing:

http.createServer(function(request, response) {    
    request.connection.addListener('close', function () {
        // callback is fired when connection closed (e.g. closing the browser)
    });
}

Other Answer2

Take a look at Socket.io. It supports the following transports with fallbacks in this order:

  1. WebSocket
  2. Adobe Flash Socket
  3. AJAX long polling
  4. AJAX multipart streaming
  5. Forever Iframe
  6. JSONP Polling

The benefit is you'll be able to handle a lot more concurrent connections than long polling alone. In addition you'll get a rich set of features like heartbeats and disconnects.

io.sockets.on('connection', function (socket) {

  // ... other socket handlers here ...

  socket.on('disconnect', function () {
    // do something to handle the disconnect
  });
});