如何维护页面之间的 WebSockets 连接? [英] How to maintain a WebSockets connection between pages?

查看:20
本文介绍了如何维护页面之间的 WebSockets 连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个脚本中,我有这个代码:

On one of my scripts I have this code:

var webSocket = window.WebSocket || window.MozWebSocket;
window.ws = new webSocket('ws://64.121.210.140:2585/consoleappsample', 'my-protocol');

哪个工作正常.但是,当用户更改页面时,我必须重新建立连接.我相信这会导致我的代码出现问题,因为如果客户端将数据发送到服务器然后更改页面,则可能无法接收到数据并且会发生竞争条件.

Which works fine. However, when the user changes pages, I have to re-establish the connection. I believe this is causing problems in my code because if the client sends data to the server and then changes pages, the data may not be received and race conditions are occurring.

我试图将 window.ws 放在全局范围内,但它似乎没有解决问题.有什么方法可以让 WebSockets 连接在页面之间保持不变,这样连接就不需要不断重新建立?

I tried to put the window.ws in global scope but it didn't seem to fix the problem. Is there any way for the WebSockets connection to persist between pages so the connection does not need to be constantly reestablished?

推荐答案

你提到的全局作用域总是和 JavaScript Context 相关的,每个窗口都会创建一个 Context(并且在从内存中卸载文档时销毁).因此,您的努力是无用的:如果用户更改页面,您将无法保持连接打开.当然,您可以将您的 web 应用程序作为单页"应用程序,使用 XMLHttpRequest/ajax/WebSocket 加载所有数据.所以,离开页面意味着离开/关闭应用程序,关闭套接字是有意义的.

The global scope you mentioned is always related to the JavaScript Context, and a Context is created for each windows (and destroyed when the document is unloaded from the memory). Therefore, your effort are useless: you can't keep a connection opened if the user change page. Of course you can have your webapp as "single page" application, where all the data are loaded using XMLHttpRequest / ajax / WebSocket. So, leaving the page means leaving / shutdown the application, and makes sense close the socket.

另一种旧方法是将您的页面放在框架中,用户仅在框架中导航(即使它占据了整个窗口的大小).这样,您就可以在最顶部的窗口中创建 WebSocket,该窗口永远不会更改(这也意味着地址栏中显示的 URL 将始终相同).

Another old approach could be put your pages in a frame, where the user navigate only in the frame (even if it takes the whole size of the window). In that way, you can create your WebSocket in the top most window, that is never changed (that also means the URL showed in the location bar will be always the same).

说到这里,我同意@dystroy:您的应用程序应该始终能够处理这种情况——用户可能会遇到一些网络问题并暂时失去连接,即使它没有离开页面.

Said that, I agreed with @dystroy: your application should be always able to handle this scenario - the user could have some network problem and lost the connection for a moment, even if it doesn't leave the page.

这篇关于如何维护页面之间的 WebSockets 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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