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.


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

// Socket Variable declaration
var mySocket;
const socketMessageListener = (event) => {

// Open
const socketOpenListener = (event) => {

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