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

走远了吗. 提交于 2019-11-30 03:39:10

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!