Connection State

The client library SDK will manage the connection for the entirety of a session. It handles the initial connection handshake, keeps authentication credentials up to date, manages connection errors, handles reconnections, transmits and processes events as they are received.

Events related to the connection state are made available throughout the service via events. You can listen to these events and react accordingly to manage your application's connection behavior.

Connection state events

To handle connection events throughout your application we create listeners.

import RelayBox from '@relaybox/client'

const relayBox = new RelayBox();

relayBox.on('connect', () => {
  console.log('Connection established');
});

relayBox.on('reconnecting', (attempt: number) => {
  console.log('Reconnecting, attempt', attempt);
});

...

await relayBox.connect();

Connection Event Handlers

Use these event listeners throughout your application to respond to connection events in real time. See below for a full list of events and the data passed to your handlers.

// Socket event types
export enum SocketEvent {
  CONNECT = 'connect',
  DISCONNECT = 'disconnect',
  ERROR = 'error',
  RECONNECTING = 'reconnecting',
  RECONNECTED = 'reconnected',
  RECONNECT_FAILED = 'reconnect_failed'
}

connect

Emitted once a connection has been established either initially or following a reconnect event.

relayBox.on('connect', () => {
  console.log('Socket connection established');
});

disconnect

Emitted in the event of a disconnection

relayBox.connection.on('disconnect', (reason: string) => {
  console.log('Socket disconnection', reason);
});

error

Emitted if a connection error is received from the server. Relaybox will attempt to reconnect with an exponential backoff up to a maximum of 10 times.

relayBox.connection.on('error', (err: Error) => {
  console.log('Socket disconnection', reason);
});

reconnecting

Emitted each time a reconnection is attempted, passing the attempt number as an argument.

relayBox.on('reconnecting', (attempt: number) => {
  console.log('Socket reconnecting, attempt', attempt);
});

reconnected

Emitted once a connection is re-established following a disconnection event.

relayBox.connection.on('reconnected', (attempts: number) => {
  console.log(`Socket reconnected after ${attempts} attempts`);
});

reconnect_failed

Emitted if the maximum number of reconnection attempts has been made without success.

relayBox.connection.on('reconnect_failed', (err: Error) => {
  console.log('Socket reconnection failed', err);
});

    On this page