node.js - 浏览器刷新时重新连接套接字连接
问题描述
我有一个使用套接字进行通信的 React 和 Node 应用程序。这工作正常,直到我刷新浏览器。我读到当您离开页面或刷新时套接字会断开连接 - 好的。
我需要在刷新时重新连接或创建新连接。我该怎么做呢?
在客户端,我有:
let socket = openSocket(window.location.href);
...
if(socket.disconnected) { //on refresh this is true
socket = openSocket(window.location.href);
socket.open(); //this never seems to connect.
}
socket.on(id, msg => { //on refresh this is disconnected
//do stuff
}
我的后端是典型的节点代码:
const socket_io = require( "socket.io" );
let app = express();
var io = socket_io();
app.io = io;
io.on( "connection", function( socket )
{
console.log( "A user connected" );
});
解决方案
问题如下:
let socket = openSocket(window.location.href);
根据您在应用程序中的位置,这可能是https://example.org/login,而不是https://example.org。
我的解决方案是
let socket = openSocket(window.location.origin);
推荐阅读
- python - 在 Altair 中将编码重置回 null
- python - 我无法理解 python 中的星号表达式
- c# - Web Api 项目中的 MVC 应用程序 Cookie AND Token 身份验证
- python - Django延迟属性操作数错误
- typescript - 如何在 Ionic 的原生音频播放功能中使用 completeCallback?
- ubuntu - 我在带有 PHP 7 的 Ubuntu 14 上安装了 cURL,但仍然调用未定义函数 curl_init()
- spring-boot - 如何处理测试用例中的异常
- java - 如何在 Java 类中声明可变数量的泛型变量?
- powershell - 术语“HOST=localhost”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称
- python - 更改导入库的环境变量