How to reconnect to websocket after close connection with HTML?

JavascriptWeb DevelopmentFront End Scripts

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();
raja
Published on 05-Apr-2018 13:02:10
Advertisements