保持与 Socket.io 的连接 [英] Keep Connection with Socket.io

查看:52
本文介绍了保持与 Socket.io 的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 socket.io-client

socket = io.connect(url ,{
    transports: ['websocket'],
    secure: true,
    'force new connection' : false,
    'reconnect' : true,
});

它可以工作,但是每次我更改或刷新页面时,websocket 连接都会断开并重新连接(显然).我的应用不是单页应用".

It works, but everytime I change or refresh page, websocket connection disconnect and reconnect (obviusly). My app is not "one-page-app".

有没有办法让连接保持活动状态?

There is a way for keep connection alive?

推荐答案

有没有办法让连接保持活动状态?

There is a way for keep connection alive?

没有.如果您允许页面在浏览器中更改,则不会.

No. Not if you allow the page to change in the browser.

当浏览器改变页面时,它会关闭所有与旧页面关联的资源(包括webSockets),然后初始化并打开新页面.你无法改变这一点.

When the browser changes pages, it will close all resources associated with the old page (including webSockets) and then it will initialize and open the new page. You cannot change that.

保持 webSocket 打开的唯一方法是将它放在一个不会改变的窗口中.这将需要转换为单页应用程序(不会更改页面)或将 webSocket 放在不会更改的框架或窗口中.您可以让用户安装浏览器扩展程序(可以保持持久连接),但我认为这不是您要问的.

The only way to keep a webSocket open is to put it in a window that does not change. That would entail either converting to a single page app (that doesn't change pages) or putting the webSocket in a frame or window that doesn't change. You could have the user install a browser extension (which can maintain persistent connections), but I assume that isn't what you're asking about.

否则,您只需管理服务器上的内容即可处理站点内的页面更改将关闭旧 webSocket 并打开一个新 webSocket 的事实.

Otherwise, you have to just manage things on your server to handle the fact that a page change within your site will close the old webSocket and open a new one.

这篇关于保持与 Socket.io 的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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