Reputation: 327
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
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
Reputation: 1168
Take a look at Socket.io. It supports the following transports with fallbacks in this order:
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