node.jsgoogle-chromesocketswebsocketreconnect

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?


Solution

  • 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.