在我使用网络套接字的聊天应用程序中,每当连接超过 1 个用户(例如 {user1: tab1, user2: tab2, user2: tab3, ...})时,关闭 tab1 时,“在线用户”状态其他选项卡(tab2,tab3,...)变为空。
但是,如果执行相反的操作,即关闭除 tab1 之外的选项卡,我的聊天应用程序可以通过实时更新“在线用户”状态来完美运行
我不知道我的代码的哪一部分出了问题,所以我提供了index.html和server.js的所有编码部分的链接
index.html
server.js
我使用的是nodejs版本10.15.0,express版本6.7.0,socket.io版本6.7.0。
我希望这么多信息就足够了。
最佳答案
我相信错误就在这里:
users.splice(users.indexOf(socket.username))
来自Array.splice documentation :
array.splice(start[, deleteCount])
If deleteCount is omitted [...] then all of the elements from start through the end of the array will be deleted.
因此,当第一个用户断开连接时,您可以从数组中删除他们以及所有后续用户。
我的猜测是你应该这样写:
users.splice(users.indexOf(socket.username), 1)
一次仅删除一名用户。
关于javascript - socket.io,使用网络套接字的聊天应用程序 - 关闭 tab1 会导致 tab2 和 tab3 中的 void "online users",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441794/