Options
All
  • Public
  • Public/Protected
  • All
Menu

Class ReconnectingClient

A wrapper around the Client class. It has almost the same methods and events as the Client class, with the exception of the connection sequence. So please refer documentation to the Client class for the similar methods.

The connection sequence looks like follows:

const client = new ReconnectingClient() // creates an instance
                🠗
      client.register('method1', handler1);
      await client.init()
      client.register('method2', handler2);
 // inits the connection:
 // ⌛ client now tries to connect to the server
                🠗
 // when the client establishes a websocket connection, it can
 // 🛑 reject the promise and emits `connectError` event if server refuses
 //   the client to connect with its token. Thus it stops any connection
 //   attempts until you execute `init` method again.
 // 👌 resolve the promise and emits `connect` event if the server accepts
 //   the connection.
                🠗
      await client.call('serverMethod' {...args});
      client.register('method3', handler3);
 // ⚡ if everything is 👌, here you can call server's methods. Note that when
 // the client isn't connected every execution of the `call` method will
 // throw an error.
                🠗
    client.addEventListener('connect', () => {console.log('😃')});
    client.addEventListener('connectError', () => {console.error('😟')});
 // 💥 when the connection to the server breaks, an `close`event will be
 // raised
 // ⌛ and the client will try to connect to the server again
 // At this point you can check the connection status via `connect` or
 // `connectError` events.
 // And, as you can see, you can register client rpc-methods everywhere in
 // the code after calling the constructor. And this methods along with
 // the events will be connected to every new inner instance of the
 // Client class

This class can register any method to call it by the server. And also can call any method on the server and receive response data. And there are some events that can help you.

The main parts of this class are:

  • init method to connect to the server
  • close event that triggers when connection to the server is lost
  • connect event that triggers when the client successfully reconnects to the server
  • connectError event that triggers when the server refuses the client to connect
  • register method to handle clients' calls
  • call method to execute clients' methods
example
import { ReconnectingClient } from '@noveo/dual-rpc-ws/client';
const client = new ReconnectingClient({
  token: 'id13',
  address: 'ws://192.168.0.80:8080'
});
try {
  await client.init();
  console.log('successfully connected for the first time!');
  client.register('hi', (params, context) => {
    console.log('client hi, call id:', context.id);
    return Promise.resolve(`${token}, hello`);
  });
  client.addEventListener('connect', () => {
    console.log('successfully reconnected!');
  });
  client.addEventListener('connectError', () => {
    console.error('server refuses to reconnect!');
  });
  client.addEventListener('close', () => {
    console.log('connection closed!');
  });
  try {
    const serverResponse = client.call('hi', {message: 'Server, hi!'});
    console.log('Hello from server', serverResponse);
  } catch(e) {
    console.error('Trouble with call', e.message);
  }
} catch(e) {
  console.error('server refuses to connect!')
}

Hierarchy

  • ReconnectingClient

Index

Constructors

constructor

Events

close

  • close(): Promise<unknown>
  • Fires when the connection with the server closes

    Returns Promise<unknown>

connect

  • connect(): void
  • Fires when the client successfully reconnects to the server

    Returns void

connectError

  • connectError(message?: undefined | string): void
  • Fires when the server refuses the client to connect in the reconnection attempt

    Parameters

    • Optional message: undefined | string

    Returns void

Properties

Private connectedForTheFirstTime

connectedForTheFirstTime: boolean = false

Private Optional instance

instance: Client

Private interval

interval: number = 3000

Private isDisconnecting

isDisconnecting: boolean = false

Private listeners

listeners: Map<Name, Map<EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined>> = new Map()

Private methods

methods: Map<Name, (params: Record<string, any> | null, ctx: RPCContext) => Promise<JSONValue> | JSONValue | undefined> = new Map()

Private params

Private serverRejected

serverRejected: string = ""

Methods

addEventListener

  • addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void
  • Parameters

    • type: string
    • listener: EventListenerOrEventListenerObject
    • Optional options: boolean | AddEventListenerOptions

    Returns void

Private attachMethodsAndListeners

  • attachMethodsAndListeners(): void

call

  • call(method: string, params?: Record<string, any>): Promise<object | [] | string | number | boolean | null>
  • Call the server method using params as one argument construction.

    throws

    one of these errors:

    Parameters

    • method: string

      The name of the remote method to call

    • Optional params: Record<string, any>

      Method arguments

    Returns Promise<object | [] | string | number | boolean | null>

    Returns a Promise with the JSON response from the client. It can be an object, an array or a primitive.

disconnect

  • disconnect(): void

dispatchEvent

  • dispatchEvent<K>(type: K, event: ReconnectingClientEventMap[K]): void
  • Type parameters

    • K: keyof ReconnectingClientEventMap

    Parameters

    • type: K
    • event: ReconnectingClientEventMap[K]

    Returns void

init

register

  • register(method: string, handler: (params: Record<string, any> | null, ctx: RPCContext) => Promise<JSONValue> | JSONValue | undefined): void
  • Register the method on the client side, handler must return an object or a Promise<object> which will be held on the server side

    example
    client.register('ping', (params) => {
      console.log('client ping', params);
      return Promise.resolve({ client: 'pong' });
    });

    You can throw an exception in the handler and on the caller side the server will catch the rejection of the calling promise.

    example
    client.register('exception', () => {
      throw new Error('client exception');
    });
    
    // server
    server.call('<YOUR_TOKEN>', 'exception', {})
      .catch((e) => console.log(e.message)); // prints "client exception"

    If the function does not return a value, a value of null will be obtained on the client side. Because there is no undefined value in the JSON representation.

    Parameters

    Returns void

removeAllListeners

  • removeAllListeners(totallyRemove?: boolean): void

removeEventListener

  • removeEventListener(type: string, listener: EventListenerOrEventListenerObject, totallyRemove?: boolean): void
  • Parameters

    • type: string
    • listener: EventListenerOrEventListenerObject
    • Default value totallyRemove: boolean = true

    Returns void

unregister

  • unregister(method: Name): void

Generated using TypeDoc