本文介绍了如何检测用户的连接丢失或他关闭了 Nodejs socket.io 中的浏览器窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Node.js 和 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)...

这个 socket.io 事件仅在用户断开连接时触发,而不是在失去连接时触发.

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.

推荐答案

有什么区别?关闭窗口,切断以太网线...对于服务器来说都是一样的:连接结束.

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

阅读 socket.io 文档:https://github.com/LearnBoost/socket.io/wiki/Exposed-events

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

socket.on('disconnect', function() {}) - 在所有情况下,当客户端-服务器连接关闭时,都会触发断开连接事件.它会在需要的、不需要的、移动的、不可移动的、客户端和服务器断开连接时触发.

您不应该依赖您的按钮,因为人们可能会在不使用该按钮的情况下断开连接.使用 disconnect 事件,一旦套接字断开连接(套接字,而不是用户,因为 Node 只知道套接字),您将必须找出谁是该套接字的所有者"并将他标记为已断开连接".或者甚至更好,等待几秒钟,然后将他标记为离线.为什么?因为即使用户只是重新加载页面或导航到另一个页面,也会触发断开连接事件.因此,如果您等待几秒钟,用户将再次在线.

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.

我也遇到了这个问题,我最终创建了一个观察者",它每 X 秒运行一次,并在用户没有任何套接字或他们似乎不在时(长时间没有活动)将用户标记为离线).

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

这篇关于如何检测用户的连接丢失或他关闭了 Nodejs socket.io 中的浏览器窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 06:25