ReconnectingWebSocket - JavaScript Library for Handling WebSocket Auto-Reconnection Elegantly

Tadashi Shigeoka ·  Sat, December 7, 2019

I’ll introduce the JavaScript library ReconnectingWebSocket that handles WebSocket auto-reconnection elegantly.

WebSocket

Background: WebSocket Auto-Reconnection Implementation is Tedious

First, as background, WebSocket auto-reconnection processing is something everyone definitely implements, but WebSocket doesn’t handle it for you, so you have to implement it yourself.

So I wondered “How do other people implement this?” and when I searched Google, I found joewalnes/reconnecting-websocket: A small decorator for the JavaScript WebSocket API that automatically reconnects, which was exactly what I needed, so I immediately rewrote the WebSocket auto-reconnection processing.

Auto-Reconnection Processing: WebSocket vs ReconnectingWebSocket

Below, I’ll introduce JavaScript sample code implementing WebSocket auto-reconnection processing with both primitive WebSocket and ReconnectingWebSocket.

WebSocket Auto-Reconnection Processing Sample Code

function connect() {
  const ws = new WebSocket('ws://localhost:8080');

  ws.onopen = () => {
    ws.send(JSON.stringify({

        //.... some message the I must send when I connect ....

    }));
  };

  ws.onmessage = (event) => {
    console.log('Message:', event.data);
  };

  ws.onclose = (event) => {
    console.log('Socket is closed. Reconnecting in 3 seconds.', event.reason);
    setTimeout(() => {
      connect();
    }, 3000);
  };

  ws.onerror = (event) => {
    console.error(event.message);
    ws.close();
  };
}

connect();

Auto-Reconnection Processing Sample Code Using ReconnectingWebSocket

function connect() {
  const ws = new ReconnectingWebSocket(
    'ws://localhost:8080',
    null,
    {
      debug: true,
      reconnectInterval: 3000
    }
  );

  ws.onopen = () => {
    ws.send(JSON.stringify({

        //.... some message the I must send when I connect ....

    }));
  };

  ws.onmessage = (event) => {
    console.log('Message:', event.data);
  };

  ws.onclose = (event) => {
    console.log('Socket is closed.', event.reason);
  };

  ws.onerror = (event) => {
    console.error(event.message);
  };
}

connect();

That’s all from the Gemba.

Reference Information