Module/ws
WebSocket client built on IXWebSocket with a simple event-driven API.
WebSocket client built on IXWebSocket with a simple event-driven API.
Import #
import * as WS from 'Module/ws';Types #
CreateOptions
Options passed to
create().urlstring - WebSocket URL to connect to.onMessage(msg: string | ArrayBuffer) => void optional - Called when a message is received.onOpen() => void optional - Called when the connection opens.onClose() => void optional - Called when the connection closes.onError(reason: string) => void optional - Called on connection error.
WebSocketHandle
Object returned by
create(). Provides methods to control the socket lifecycle.start() => void - Open the connection.send(text: string) => void - Send a text message.close() => void - Close the connection gracefully.stop() => void - Stop the connection.destroy() => void - Release all resources.setAutoReconnect(enabled: boolean) => void - Enable or disable auto-reconnect (default: disabled).
Functions #
create
Creates a socket instance. Does not start the connection until
start() is called.- Stores callbacks; they are optional. Messages are delivered on the JS thread.
create(options: CreateOptions): WebSocketHandledrain
Process pending socket events and dispatch to callbacks. Normally unnecessary because the engine calls the update hook each frame.
drain(): voidExample #
Connect to an echo server with auto-reconnect enabled, send a message on open, and log incoming messages. This is the standard pattern for setting up a persistent WebSocket connection.
import * as WS from 'Module/ws';
import * as Log from 'Helix/Log';
const sock = WS.create({
url: 'wss://echo.websocket.events',
onOpen: () => { Log.info('open'); sock.send('hello'); },
onMessage: (m) => Log.info('msg: ' + String(m)),
onClose: () => Log.info('closed'),
onError: (e) => Log.error('ws error: ' + e)
});
sock.setAutoReconnect(true);
sock.start();Notes #
createstores callbacks; they are optional. Messages are delivered on the JS thread.