刷新后保持 WebSocket 连接处于活动状态 [英] Keep WebSocket connection alive after refresh

查看:141
本文介绍了刷新后保持 WebSocket 连接处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实时应用程序,它在 java spring 服务器和浏览器之间使用了 WebSockets.是否有一种方法可以在页面刷新后保持 Websocket 连接处于活动状态?

I have a real time application which used WebSockets between java spring server and browser. Is there a method to keep the Websocket connection alive after page refresh ?

这是我的 javascript 代码:

This is my javascript code:

consumerWebSocket = new WebSocket("wss://" + window.location.host + 
"/myWebSocketConnection");

consumerWebSocket.onopen = function () {
    sendThroughWS(consumerWebSocket, "Send this message from browser to server");

};

推荐答案

不,你不能.问题是 websockets 所处的上下文仅限于您正在显示的页面.一旦您刷新页面或导航到另一个页面,上下文(以及 websocket)就会被销毁.

No, you cannot. The problem is that the context a websockets lives in is limited to the page you are displaying. As soon as you refresh the page or navigate to another, the context (and therefore the websocket) is destroyed.

防止破坏的解决方案是创建某种单页应用程序.新内容将加载到现有页面中,并且不会重新加载 websocket.

A solution to prevent destroying is to create some sort of Single page Application. The new content would be loaded into the existing page and the websocket is not reloaded.

另一种方法是使用框架.您可以将 Websocket 放在(隐藏的)框架中,然后使用另一个框架进行导航.这样,套接字可以保持活动状态,您可以在不重新加载 websocket 的情况下浏览页面的其余部分.

Another way is using frames. You can put your Websocket in a (hidden) frame and just navigate using another frame. This way the socket can be stay alive and you can navigate through the rest of your page without a websocket reload.

这篇关于刷新后保持 WebSocket 连接处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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