I can't get the websocket to automatically reconnect unless I refresh the browser tab

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?

Answer №1

If you're encountering difficulties, consider utilizing the setInterval method. Give this code snippet a try, and feel free to adjust it as needed.

var endpoint = `ws://${window.location.hostname}/ws`;
var webSocket, timer = null;

function initializeWebSocket() {
  console.log('Attempting to establish a WebSocket connection...');
  webSocket = new WebSocket(endpoint);
  webSocket.onopen    = onOpen;
  webSocket.onerror    = onError;    //  new
  webSocket.onclose   = onClose;
  webSocket.onmessage = onMessage; // <-- include this line
}

function onOpen(event) {    
  clearInterval(timer) // <= improved
  console.log('Connection established');
}

function onError() {   // <= New
       timer = setInterval(initializeWebSocket, 1000 * 60);        
};

function onClose(event) {
  console.log('Connection terminated');
  timer = setInterval(initializeWebSocket, 1000 * 60); // <=new
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on retrieving a specified string from within an array of strings

I need help extracting the inner string from this array within a string: '["sgrdalal21"]' Can someone provide guidance on how to accomplish this? ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

javascript: unable to modify currentTime in <audio> tag

Struggling to create a progress bar for my HTML5 audioplayer and implement a function to change the playing track's time by tapping. I opted to use input[range], but encountering an issue where the current play time does not update when tapping on the ...

Incorporating an element into a nested array

I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one. This is my current array: const ...

Is it a mistake? Using React and ES6 without Babel may not be the

Have you ever considered bundling all of your classes into a single file without using Babel to polyfill it to ES5? If the browser doesn't support ES6, you could then use Babel in the browser or load the polyfilled bundle and manually add the dependen ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

The angular view is lacking a CSS class

index.html: <div ng-view="myview.html"></div> myview.html: <table class="table table-striped table-hover"> <tr> <td>Name</td> <td>Product</td> </tr> <tr ng-repeat="deal in deals" class="clickableR ...

react-swiper does not trigger a re-render

function WorkSpace() { const dispatch = useDispatch(); const edit = useSelector((state)=>(state.workSpace.edit)); const currentMode = useSelector((state)=>(state.workSpace.currentMode)); useEffect(()=>{ const swiper = docu ...

Say goodbye to my HTML5 creations

I am currently working on an HTML5 grid project that involves implementing a rectangle select tool for use within the grid. Everything is going smoothly, except for the fact that when I attempt to use the rectangular select tool, the grid disappears from t ...

Rerender not occurring after array splice with React hooks setter

My parent component structure is as follows: import React from "react"; import Test from "./Test"; function App() { const [configs, setConfigs] = React.useState([1, 2, 3]) return ( <div> ...

What steps should I take to address the issues with my quiz project?

I've been working on a new project that involves creating a quiz game. I came across some code online and decided to customize it for my needs. However, I'm encountering some issues with the functionality of the game. Right now, the questions ar ...

Getting Started with NPM Package Initialization in Vue

I'm attempting to incorporate the v-mask package into my Vue project using npm. Following the documentation, I executed npm install v-mask, but I am unsure where exactly to initialize the code. I tried placing it in the main.js file: import { createAp ...

Creating custom ExpectedConditions with Protractor for detecting attribute changes

I've been working on creating a custom ExpectedConditions method that can wait for an element attribute to change. Here is the approach I came up with: const CustomExpectedCondition = function() { /** * Check if element's attribute matches ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

Tips for validating a dynamically created form with Bootstrap tabs using jQuery

For my project, I am dynamically creating an HTML form using jQuery. The page consists of five tabs, each with separate previous and next buttons. These tabs are designed using Bootstrap. Can someone please suggest the easiest way to validate this page? Fo ...

Is there a method to retrieve a value from a node.js server when a div is clicked?

This is the EJS file I've created: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Sart Plug</title> <script src="http://code.jquer ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...