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

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

问题描述

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

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

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



我试图把 window.ws 放在全局范围内,但似乎没有解决问题。是否有任何方法让WebSockets连接在页面之间持续存在,因此连接不需要不断重新建立? 解决方案

全局您提到的范围始终与JavaScript上下文相关,并且会为每个窗口创建一个上下文(并在文档从内存中卸载时销毁)。因此,您的努力是无用的:如果用户更改页面,则无法保持连接打开。
当然,您可以将Web应用程序设置为单页应用程序,其中所有数据均使用XMLHttpRequest / ajax / WebSocket加载。所以,离开页面意味着离开/关闭应用程序,并且合理地关闭套接字。



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

<说:我同意@dystroy:你的应用程序应该总是能够处理这种情况 - 用户可能有一些网络问题,并暂时失去连接,即使它不离开页面。


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.

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?

解决方案

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.

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

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天全站免登陆