ModulesWebSocket Module

Websocket

The WebSocket module in ZDK provides users with a seamless connection to WebSockets. It is dedicated to ensuring that packets are accurately read and dispatched. Notably, in cases where the connection is disrupted, this module possesses a built-in mechanism to attempt reconnection, ensuring persistent communication and enhanced user experience.

Dependencies
  • core
  • user

Initialization

To initialize, supply the User Module and consider including the “WebSocketReconnection” plugin for seamless reconnection after internet disruptions. This plugin ensures the WebSocket connection is automatically reestablished.

file.ts
const webSocket = new createWebSocket({
 plugins: [WebSocketReconnection],
 userModule: user,
 config: {
  host: 'ws.dev.zu.casa'
 }
});

Actions

open

Action type

() => Promise<void>

Description

Executes the process to establish a WebSocket connection. It is essential to ensure that the User Module is correctly configured prior to invoking this action. For robust connection handling, especially in cases of intermittent internet connectivity, it is recommended to utilize the “WebSocketReconnection” plugin, which will automatically attempt to re-establish the connection at regular intervals without the need for manual re-invocation of the open action.

Return value

A promise that resolves when the WebSocket connection is successfully established.

Possible errors
  • ActionCallError - WebSocket is already connecting or connected. Use disconnect before.
  • ActionCallError - Provided UserModule is not set up - use open action on UserModule.
  • ConnectionFailedError - WebSocket connection canceled. This error occurs when the connection to the WebSocket server fails for any reason. With the WebSocketReconnection plugin, reconnection attempts will occur automatically every few seconds.

close

Action type

() => void

Description

Initiates the closure or termination of the active WebSocket connection. This action should be used to explicitly close the connection when it is no longer needed or when the application is preparing to shut down or restart its connection processes.

Data (Getters)

status

Getter output type: 'idle' | 'loading' | 'connected' | 'interrupted'

Description

This getter allows querying the current status of the WebSocket module, which mirrors the state of the WebSocket connection:

  • idle - The WebSocket is inactive, waiting for a command to initiate a connection.
  • loading - The WebSocket is in the process of establishing a connection.
  • connected - A WebSocket connection has been established successfully.
  • interrupted - The connection has been lost. If the WebSocketReconnection plugin is in use, reconnection attempts will commence automatically.