Search docs
Search guides, modules and symbols
Modules

Docs / API / Modules / ws

WebSocket

Network

@s2script/sdk/ws

Client WebSocket. send returns boolean admission — false means closed, oversized, or full; true is queued, not delivered.

Import

import { WebSocket } from "@s2script/sdk/ws";

Author-time types ship in the npm package; the engine injects the runtime at plugin load. Add @s2script/sdk to your plugin's dependencies.

API reference

Generated from the shipped type definitions.

interface
WebSocket

An open WebSocket connection — a per-plugin handle over a copied message stream (no live socket crosses to JS).

onMessage(handler: (data: string) => void): void
— Register a handler invoked for each inbound text frame.
onClose(handler: (code: number, reason: string) => void): void
— Register a handler for connection close; code/reason come from the close frame.
onError(handler: (err: string) => void): void
— Register a handler for a transport error; err is the error text.
send(data: string): boolean
— Send a text frame. Returns false if closed, oversized, or the connection/global outbound budget is full.
close(): void
— Close the connection.
interface
WebSocketInit

Options for WebSocket.connect.

headers?: Record<string, string>
— Extra headers to send on the opening handshake — the usual reason being a credential the server requires, e.g. Authorization: Bearer <token>. Headers the handshake owns are refused, and the connect rejects rather than silently dropping them: Host, Connection, Upgrade, any Sec-WebSocket-*, Content-Length, Transfer-Encoding. Values containing control characters are refused for the same reason.
const
WebSocket

Entry point for opening WebSocket connections.

connect(url: string, init?: WebSocketInit): Promise<WebSocket>

Connect to a WebSocket server (wss:// for TLS) off the game thread.

Returns — Resolves on the open handshake with the live WebSocket handle.

Throws — Rejects on connect failure (bad URL, refused, TLS/handshake error, or a refused header).

import { WebSocket } from "@s2script/sdk/ws";
const ws = await WebSocket.connect("wss://ws.postman-echo.com/raw");
ws.onMessage((data) => { console.log("echo:", data); ws.close(); });
ws.send("hello-from-s2script");
// A server that authenticates the handshake rather than the first frame.
const ws = await WebSocket.connect("wss://maul.example/v2/ws", {
  headers: { Authorization: `Bearer ${jwt}` },
});
Back to modules All packages