Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect that user's connection is lost or he closed the browser window in Nodejs socket.io

I have a chat application on Node.js and Socket.io, user can connect and disconnect with a button... I am having a list of online users which is perfectly managed with the help of my defined events that user trigger.

But the problem is I am unable to detect if the user has lost his connection or closed the browser window without disconnecting himself manually(by the disconnect button)...

This socket.io event is fired only when user disconnects himself not when he lost his connection.

socket.on('disconnect',function(){
   console.log('user disconnected');  });

I want some really good mechanism to keep an eye on users in order to update my Online users list.

like image 216
TaLha Khan Avatar asked Apr 30 '13 06:04

TaLha Khan


People also ask

How do you check user is online or not in socket IO?

on("online", (userId) => { console. log(userId, "Is Online!"); // update online status }); // USER IS OFFLINE socket. on("offline", (userId) => { console. log(userId, "Is Offline!"); // update offline status }); });

Does node JS run in the browser?

js is a server-side JavaScript run-time environment. It's open-source, including Google's V8 engine, libuv for cross-platform compatibility, and a core library. Notably, Node. js does not expose a global "window" object, since it does not run within a browser.


1 Answers

And what's the difference? Closing the window, cutting the ethernet wire... it's all the same for the server: end of connection.

Reading the socket.io docs: https://github.com/LearnBoost/socket.io/wiki/Exposed-events

socket.on('disconnect', function() {}) - the disconnect event is fired in all cases, when the client-server connection is closed. It fires on wanted, unwanted, mobile, unmobile, client and server disconnects.

You should not rely your button, as people can disconnect without using that button. Use the disconnect event and once a socket disconnects (a socket, not a user, cause Node just knows about sockets) you will have to find out who was the "owner" of that socket and flag him as "disconnected". Or even better, wait for a few seconds and then flag him as offline. Why? Because the disconnect event will trigger even if the user just reloads the page, or navigates to another one. So if you wait a few seconds the user will be online again.

I had this problem too, and I ended up creating a "watcher" that runs every X seconds and flags users as offline when they don't own any socket or when they seem to be away (no activity for a long time).

like image 122
Salvatorelab Avatar answered Oct 05 '22 22:10

Salvatorelab