How to reconnect to websocket after close connection with HTML?


Recreate the socket to reconnect it. The websockets are designed to stay open. 

You can also go with the method to have the server close the connection. Through this, the websocket will fire an onclose event and would amazingly continue attempting to make the connection.

In addition, when the server is listening again the connection will be automatically reestablished.

Example

You can try to run the following code to reconnect to WebSocket −

// Socket Variable declaration
var mySocket;
const socketMessageListener = (event) => {
   console.log(event.data);
};

// Open
const socketOpenListener = (event) => {
   console.log('Connected');
   mySocket.send('hello');
};

// Closed
const socketCloseListener = (event) => {
   if (mySocket) {
      console.error('Disconnected.');
   }
   mySocket = new WebSocket('ws://localhost:8080');
   mySocket.addEventListener('open', socketOpenListener);
   mySocket.addEventListener('message', socketMessageListener);
   mySocket.addEventListener('close', socketCloseListener);
};
socketCloseListener();

Updated on: 25-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements