【问题标题】:Reconnect socket connection when browser refresh浏览器刷新时重新连接套接字连接
【发布时间】:2020-09-03 04:31:09
【问题描述】:

我有一个使用套接字进行通信的 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.js reactjs socket.io


    【解决方案1】:

    问题如下:

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

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

    我的解决办法是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多