问题描述
我有
- 1个PHP服务器(服务于http请求)和
- 1个节点。 js发布更新的数据消息(每个连接带有websocket)。
php服务器设置其cookie。在一个浏览器中,此cookie可在所有选项卡上使用。
当浏览器向域打开2个选项卡时,只有一个cookie标识浏览器,但有1条消息的更新数据必须发送到每个选项卡。
- 区分选项卡的传统方法是什么?
- 我是否应该使用另一个cookie(由node.js管理)来区分每个浏览器选项卡?
将我的评论变成答案...
每个选项卡都有单独的websocket 。这样一来,您就可以区分不同的标签。如果您要在服务器中的每个标签上保留单独的状态,并且要允许同一用户进行多个连接,则必须保留每个websocket连接的状态(可以使用websocket ID),而不是每个用户。
您不需要为每个标签创建单独的cookie,因为websocket本身已经充当了每个标签的唯一ID。
您还没有说过您的应用程序是否希望所有选项卡中的状态相同,或者每个选项卡具有不同的状态,并且您会根据以下情况在服务器端处理不同的事情欲望。如果希望所有选项卡都接收相同的数据,则每当要向客户端发送数据时,都必须查找与给定用户关联的所有websocket,并将相同的数据发送给他们。
如果您希望每个选项卡独立运行,则只保留每个websocket的服务器端状态,并仅向响应所属的websocket发送响应,而不是与该用户关联的所有websocket。 / p>
与SO上的几乎所有问题一样,如果您告诉我们更多关于您实际在做什么的信息,而不是进行理论上的对话,则更容易回答具体问题。例如,如果我们知道您的应用应如何与不同的标签一起使用,那么我们就会知道要遵循的行为路径。
I have
- 1 PHP server (serving http request) and
- 1 node.js publishing updated data messages (with websockets to each connection).
The php server setup its cookie. In one browser, this cookie is available across all tabs.
When a browser has 2 tabs opened to the domain, there is only one cookie identifying the browser, but 1 message of updated data must be sent to each tabs.
- What is the traditional way to distinguish between tabs ?
- Should I use another cookie (managed by node.js) to distinguish between each browser tabs ?
Turning my comment into an answer...
There's a separate websocket for each tab. That's how you distinguish different tabs from each other. If you're keeping separate state per tab in your server and you want to allow multiple connections by the same user, then you have to keep the state per websocket connection (you can use the websocket id), not per user.
You don't need to create a separate cookie per tab because the websocket itself already serves as the unique id for each tab.
You haven't said if your app wants identical state in all tabs or if each tab has different state and you would handle things a bit differently on the server side based on the desire. If you want all tabs to receive the same data, then whenever you want to send data to a client, you have to find all websockets that are associated with a given user and send the same data to them.
If you want each tab to behave independently, then you just keep server-side state per websocket and send a response only to the websocket that the response belongs to, not all websockets associated with that user.
As with nearly all questions here on SO, it's a lot easier to answer more specifically if you tell us more about what you're actually doing rather than having a theoretical conversation. For example, if we knew how your app was supposed to work with different tabs, then we'd know which behavior path to follow.
这篇关于websocket如何处理同一浏览器的两个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!