简体   繁体   中英

Detect client's disconnection WebSocket

I'm using WebSocket & nodeJs. I can detect user's connection and present it, but I can't detect user's disconnetion. The method on('close',function()....) happens when I shut down the server and not when a user closes the tab or something. What can I do? I realy don't know how to do it right now. Thank you all! Hoping you'll help me.

To detect socket disconnection, I use this method which works fine :

socket.once('disconnect', function () {
    // socket is disconnected
});

Or

socket.on('disconnect', function () {
    // socket is disconnected
});

Hope it helps.

You should implement heartbeat requests (inside websocket connection) from client to server (every 20-30 sec) and limit connection to some period (40-50 sec) - this can be done in web server (or even load balancer settings).

When server find that there is no heartbeat request it means that this connection is broken - client closed tab or something.

Updated : oh! Seems socket.io have heartbeat implementation, so my answer was a bit common.

io.sockets.on('connection',function(socket){
  socket.on('disconnect', function(){
    // Your stuff here
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM