简体   繁体   English

将Websocket-Connection保留在多个页面上

[英]Hold Websocket-Connection over several pages

I need an idea in designing a complex html/javascript(jQuery) system communicating with my C++-Webserver. 我需要一个设计与我的C ++-Webserver通信的复杂html / javascript(jQuery)系统的想法。

Until now i have a main index.html and I load Submodules by events: 到目前为止,我有一个主要的index.html,并通过事件加载子模块:

$(".MainButton").click(function(){
   $("#swap").load($(this).attr('alt'));
});

The problem is now that every Submodule needs a Websocket Connection and I dont want to open a new Connection for every Submodule that I am loading. 现在的问题是,每个子模块都需要一个Websocket连接,而我不想为正在加载的每个子模块打开新的连接。

Is it possible to open a global Websocket connection.. 是否可以打开全局Websocket连接。

var ws = new WebSocket("ws://localhost:800/stream");

.. and use ws in every subpage? ..并在每个子页面中使用ws?

Thank you very much. 非常感谢你。

Your question's title and content are different. 您问题的标题和内容是不同的。 As for the content, if you load HTML fragments (rather than page) by jQuery's load method, these fragments are merged into the document and only that document exists as a result. 至于内容,如果您通过jQuery的load方法加载HTML片段(而不是页面),则这些片段将合并到文档中,因此仅存在该文档。 If it's your case, why don't you just open that connection on main.html by making ws a global variable of window and use it in submodules? 如果是您的情况,为什么不通过将ws设置为window的全局变量并在子模块中使用它而仅在main.html上打开该连接? As long as submodule's URI is same origin or cross origin with CORS, it can access and manipulate ws of main.html. 只要子模块的URI与CORS是相同的源或跨源的,它就可以访问和操作main.html的ws

However, if you insist connection should be held over several pages including a refresh of main.html as your question's title literally, it's not possible for now unless you make use of Single-page application . 但是,如果您坚持要在多个页面上保持连接,包括从字面上刷新main.html作为问题的标题,那么除非您使用Single-page application,否则现在不可能。 For the details, see the followings: 有关详细信息,请参见以下内容:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM