Skip to content

cxWebSocket

Auto-generated documentation from JSDoc comments

Functions

send(data) ⇒ Promise.<void>

Sends data through the WebSocket connection.

Kind: global function
Returns: Promise.<void> - Resolves when the data has been sent.

Param Type Description
data string | ArrayBuffer | Blob The data to send through the WebSocket.

Example

// Send a JSON object to the connected client
import * as socket from 'cxWebSocket';
socket.send({
    action: 'DashboardData',
    data: 'Socket Test',
});

on(eventName, callback) ⇒ void

Registers an event listener for WebSocket events. Polls for events at 100ms intervals and invokes the callback when matching events occur.

Kind: global function

Param Type Description
eventName string The name of the event to listen for (e.g., 'message', 'tick', 'elected', 'demoted', 'renew', 'close').
callback function The callback function to invoke when the event occurs.
callback.event Object The event object passed to the callback.

Example

// Listen for tick events (fired every second)
import * as socket from 'cxWebSocket';
socket.on('tick', async () => {
    console.log('tick check');
    socket.send({
        action: 'DashboardData',
        data: 'Socket Test',
    });
});

// Listen for incoming messages from the client
socket.on('message', async (event) => {
    console.log('Received:', event.data);
});

// Listen for leader election events (distributed scenarios)
socket.on('elected', async () => {
    console.log('This instance is now the leader');
});

waitForClose() ⇒ Promise.<void>

Wait for the WebSocket connection to close. Returns a promise that resolves when the 'close' event is emitted. This is essential for keeping the function alive and preventing premature termination.

Kind: global function
Returns: Promise.<void> - Resolves when the WebSocket connection is closed.
Example

// Basic usage - wait for client to disconnect
await waitForClose();
console.log('WebSocket connection closed');
Example
// Management socket pattern - keep connection open while handling events
import * as socket from 'cxWebSocket';
export async function managementSocket(data) {
    let counter = 0;

    socket.on('tick', async () => {
        console.log('tick check');
        socket.send({
            action: 'DashboardData',
            data: 'Socket Test',
        });
        counter++;
    });

    // Keep the connection open until the client disconnects
    return await socket.waitForClose();
}