在socket.io中管理多个选项卡(但相同的用户) [英] Manage multiple tabs (but same user) in socket.io

查看:507
本文介绍了在socket.io中管理多个选项卡(但相同的用户)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用socket.io时遇到了一些问题,我不知道如何解决它。我有一个带有socket.io的登录系统的应用程序来管理用户交互。我还有一个数组来管理所有活动的websocket会话。此数组存储一对session.id => username。

I'm having some problems with socket.io, and I have no idea how to solve it. I've an app with a login system with socket.io to manage user interactions. Also I've an array to manage all active websocket sessions. This array stores a pair session.id => username.

当用户打开具有相同页面的新选项卡(或使用websocket的其他页面)时,问题就开始了。这会导致数组中的用户名条目重复。

Problems begin when a user opens a new tab with the same page (or a different page that uses the websocket). This cause a duplicate username entry in the array.

{id1, username}
{id2, username}

当套接字向用户发送消息时,它只发送到数组的第一个会话ID,所以只一个标签收到消息。

When socket sends a message to the user, it sends only to the first session id of the array, so only one tab receives the message.

我试图更改新连接的套接字ID以匹配另一个,但它不起作用。

I've tried to change the socket id of the new connection to match the other, but it doesn't work.

socket.id = sessionId of the other websocket;

我认为另一种解决方案是将消息发送到所有打开的会话,但我认为这不是最好的办法。

I think another solution is to send the message to all the open sessions, but I think it's not the best way to do that.

谢谢。

推荐答案

听起来就像你可能在你的问题中引用套接字ID,而不是会话ID。如果您有快速会话,则可以使用会话ID,无论打开多少个选项卡,只要它们使用相同的浏览器并且它不处于私有模式,它就会相同。看一下这个问题,了解如何在socket.io中启用会话。

It sounds like you may be referring to the socket id in your question, not the session id. If you have an express session you can use the session id, which will be the same regardless of how many tabs are open as long as they use the same browser and it's not in "private" mode. Take a look at this question for how to enable sessions in socket.io.

socket.io和session?

更新:
当你'重新保存会话ID,您将其与用户的昵称和连接的套接字相关联。然后,您可以遍历每个套接字并发送消息。如下所示:

Update: When you're saving the session id, you'll associate it with the user's nickname and the connected sockets. Then you can iterate through each socket and send the message. Something like the following:

[
    {sessionId: '12345', nickname: 'timmay!', socketIds: [1, 2, 3]},
    {sessionId: '23456', nickname: 'pete', socketIds: [4, 5, 6]}
]

当建立另一个连接时,将新套接字ID推送到socketIds数组,当用户断开连接时,删除id。

When another connection is established you push the new socket id into the socketIds array, and when a user disconnects you remove the id.

另一种选择可能是每个会话每个用户只允许一个选项卡。您可以存储单个socketId,当新套接字连接到同一个用户时,您可以断开原始套接字并使用新套接字。

Another option might be to only allow one tab per user per session. You can store a single socketId and when a new socket connects for the same user, you can disconnect the original socket and use the new one instead.

这篇关于在socket.io中管理多个选项卡(但相同的用户)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆