user11810894
user11810894

Reputation:

How to reconnect a socket using native WebSocket library in Chrome

I have this:

<script>

  const socket = new WebSocket('ws://localhost:3702');    

  socket.addEventListener('open', function (event) {
    console.log('connection made to server:', event);
  });

  socket.addEventListener('message', function (event) {
    console.log('ws client received message:', event);
    location.reload();
  });

</script>

it won't auto-reconnect, if the server restarts. What is the best way to reconnect to the server?

Upvotes: 2

Views: 4158

Answers (2)

Ari
Ari

Reputation: 7556

You need to detect the connection-close event and write a reconnect function to try to reconnect to the server:

socket.addEventListener('close', function (event) {
    console.log('Disconnected!');
    reconnect(); //----------> tries to reconnect through the websocket
  });

Notice that it might take a long time for the close event to fire. In which case you can implement a simple ping-pong method as described here to detect the connection is dropped (instead of the close event).

You can find a simple implementation of a reconnect function here.

Upvotes: 1

user11810894
user11810894

Reputation:

So looks like there is no reconnect option, which makes sense for a lower-level library. This reconnect logic worked fine:

  const createConnection = () => {

    const socket = new WebSocket('ws://localhost:3702');

    socket.addEventListener('open', function (event) {
      console.log('connection made to server:', event);
    });

    socket.addEventListener('close', function (event) {
      console.log('connection closed:', event);
      socket.close();
      setTimeout(createConnection, 2500);  // reconnect here
    });

    socket.addEventListener('message', function (event) {
      console.log('ws client received message:', event);
      location.reload();
    });

  };

once the connection is closed ('close' event occurs because the server restarts), then we wait 2.5 seconds and then attempt to reconnect. If the reconnect fails, then the close event re-fires, so we just try again 2.5 seconds later.

Upvotes: 1

Related Questions