浏览器刷新时重新连接套接字连接

时间:2020-09-02 20:07:53

标签: node.js reactjs socket.io

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

1 个答案:

答案 0 :(得分:0)

问题出在以下方面:

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

取决于您在应用中的位置,它可能是https://example.org/login,而不是https://example.org

我的解决方法是

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