Currently, I have a web server running websockets on an ESP8266. The operations are smooth on both the client and server sides, with data being sent and received. However, when the server side disconnects due to a power cycle or code upload, the client (Chrome) fails to reconnect to the websocket. Even though the console log indicates that it is attempting to connect to the websocket after reloading or refreshing the web page, the reconnection does not occur. The only workaround I have discovered is to close the tab and start a new session.
My code is largely based on the tutorial provided by Random Nerd Tutorials
var gateway = `ws://${window.location.hostname}/ws`;
var websocket;
function initWebSocket() {
console.log('Trying to establish 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 established');
}
function onClose(event) {
console.log('Connection closed');
setTimeout(initWebSocket, 2000);
}
Does the code above lack any necessary components to enhance its reliability?