karter
karter

Reputation: 327

Detecting close of client connect in node.js

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?

Upvotes: 16

Views: 5904

Answers (2)

karter
karter

Reputation: 327

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)
    });
}

Upvotes: 14

JamesOR
JamesOR

Reputation: 1168

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
  });
});

Upvotes: 1

Related Questions