I ran into a situation where I need to leave the connection open if the user pressed F5 in the browser, disconnect should work only if for example the user closed the tab or browser. This is necessary, for example, if a person visits the site, and when connecting a socket, I notify everyone who is online that such and such a user has logged on to the site. In the standard situation, each time the page is refreshed, the connection event will be triggered and will notify everyone who is online each time.

How to solve this problem?

PS As an option, you can consider this example .

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

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

  • 2
    The connection on any breaks. because the browser, when reloading the page, unloads all the scripts and then launches them on a new one. And the connection can break just for network problems, and not just for F5 and almost immediately reconnect if the client part of course does. Timeout seems to me the best solution - Mike
  • 2
    You cannot do without a timer for one simple reason: you need to have a certain amount of time when the newly logged in user will not be considered as having left. And the event of a real user outage should occur only after the end of this time period - Dmitriy Simushev
  • With F5, disconnect may not occur, because browsers “for speeding up” keep the keep alive sockets (cached), even if the remote server has not set up keep. You have to send the flow code by the exit handler, or set a timer on the page (if you stopped downloading) - nick_n_a
  • one
    And what session is not suitable? At least 100 times press F5 data in the session will still be. - hitcode 4:05 pm
  • You seem to have read only half the question. After the reboot, the session will remain, but with the actual departure of the person from the chat, he still needs to be nailed somehow. And in this case, sessions are not at all a solution to the problem - Dmitriy Simushev

1 answer 1

  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 does not come from anywhere in XX seconds - you make the user offline.
  4. As soon as the user takes any action on the front, a ping will come to the server and you will send all messages that the user is online again.