javascript – Socket.io and proper disconnect

Question:

I came across a situation where I need to leave the connection open if the user pressed F5 in the browser, disconnect should only work if the user, for example, closed the tab or browser. This is necessary, for example, if a person visits the site, and when the socket is connected, I notify everyone who is online that such and such a user has entered the site. In a standard situation, every time the page is refreshed, the connection event will fire, and will notify everyone who is online every time.

How to solve such a problem?

PS As an option, you can consider this example .

But, I don’t really like this approach, although you can set the timer to disconnect , and when connecting, check in the array with authorized clients if there is one with such a sessid, and if there is, then do not do the actions that are in connection .

But, for some reason, I believe that there are more interesting options for solving the problem. I ask local gurus to unsubscribe about this)

Answer:

  1. The front every X seconds sends a ping to the server that it is online. Online is checked at the front (mouse movement in the window, etc.)
  2. Each open tab sends such a ping.
  3. If the ping did not come from anywhere for XX seconds, you make the user offline.
  4. As soon as the user makes some action on the front, then a ping will come to the server and you will send messages to everyone that the user is online again.
Scroll to Top
AllEscort