KryonOSDocs
Connectivity & Networking

WebSocket Client

Real-time bidirectional WebSocket communication from KryonOS JavaScript apps.

9. Global Class: WebSocket (Real-Time Communication)

KryonOS features a W3C-compatible, hardware-accelerated WebSocket client engine with native C++ FreeRTOS ping/pong keep-alive (every 20 seconds).

9.1 Constructor

// Basic connection
var ws = new WebSocket("ws://echo.websocket.events");
// Or secure wss://
var ws = new WebSocket("wss://echo.websocket.events");

// With custom subprotocol
var ws = new WebSocket("wss://example.com/socket", "chat-v1");

// With options object (subprotocols + custom HTTP handshake headers like Authorization)
var ws = new WebSocket("wss://api.example.com/v1/stream", {
    protocol: "stream-v1",
    headers: {
        "Authorization": "Bearer YOUR_JWT_TOKEN",
        "X-Custom-Client": "KryonOS-v2"
    }
});

9.2 Properties & Event Callbacks

  • ws.readyState: 0 (CONNECTING), 1 (OPEN), 2 (CLOSING), 3 (CLOSED).
  • ws.url: Connected URL string.
  • ws.onopen = function(): Triggered when the WebSocket handshake succeeds.
  • ws.onmessage = function(event): Triggered when a frame is received.
    • event.data: Received payload string.
    • event.isBinary: Boolean (true if binary frame, false if text frame).
  • ws.onerror = function(error): Triggered on socket errors or unexpected connection termination.
  • ws.onclose = function(event): Triggered when the socket closes.
    • event.code: Number close code (e.g., 1000 Normal Closure, 1006 Abnormal Closure / Network Lost).
    • event.reason: String closure description or server reason.
    • event.wasClean: Boolean (true if cleanly closed with a close frame, false if dropped or aborted).

9.3 Methods

  • ws.send(data): Transmits data to the remote server.
    • Passing a String sends a UTF-8 text frame.
    • Passing an Array of numbers (e.g., [0x01, 0x02, 0xFF]) or raw buffer sends a binary frame.
  • ws.close([code = 1000], [reason = ""]): Gracefully closes the WebSocket with optional W3C status code and reason string.
    • Example: ws.close(1000, "User logged out");
  • ws.poll(): Explicitly pumps the socket and dispatches pending events (also automatically pumped inside System.delay()).