Websocket 不会重新连接,除非我关闭浏览器选项卡并重新启动它

Websocket won't reconnect unless I close the browser tab and restart it

我有一个网络服务器,在 ESP8266 上设置了网络套接字。该应用程序在客户端和服务器端都运行良好,可以发送和接收数据。但是,如果服务器端断开连接(重启或上传新代码),客户端 (Chrome) 将不会重新连接到 websocket。我可以 reload/refresh 网页,它声称(根据控制台日志)连接到 websocket,但它没有。我发现唯一可行的解​​决方案是关闭选项卡,然后重新启动新会话。

我的代码主要基于 Random Nerd Tutorials

中的教程
var gateway = `ws://${window.location.hostname}/ws`;
var websocket;

function initWebSocket() {
  console.log('Trying to open a WebSocket connection...');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {
  console.log('Connection opened');
}

function onClose(event) {
  console.log('Connection closed');
  setTimeout(initWebSocket, 2000);
}

上面的代码中是否缺少某些使其更可靠的东西?

您可能需要使用 setInterval。试试这个,你可能需要稍微调整一下。

var gateway = `ws://${window.location.hostname}/ws`;
var websocket, sockTimer=null;

function initWebSocket() {
  console.log('Trying to open a WebSocket connection...');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onerror    = onError;    //  new
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {    
  clearInterval(sockTimer) // <= better
  console.log('Connection opened');

}
function onError() {   // <= New
       sockTimer = setInterval(init, 1000 * 60);
                
};
function onClose(event) {
  console.log('Connection closed');
  //setTimeout(initWebSocket, 2000);
sockTimer = setInterval(initWebSocket, 1000 * 60); // <=new
}