首页 > 解决方案 > 浏览器刷新时重新连接套接字连接

问题描述

我有一个使用套接字进行通信的 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" );
});

标签: node.jsreactjssocket.io

解决方案


问题如下:

let socket = openSocket(window.location.href);

根据您在应用程序中的位置,这可能是https://example.org/login,而不是https://example.org

我的解决方案是

let socket = openSocket(window.location.origin);

推荐阅读