Networking & Web Services
WebSocket Client
Full-duplex real-time WebSocket client API for telemetry streaming, remote control, and multiplayer messaging in KryonOS.
Global Class: WebSocket
The WebSocket global class provides a persistent, full-duplex TCP communication channel adhering to RFC 6455. It supports both plain (ws://) and TLS-encrypted (wss://) sockets.
Socket driver source code is maintained in the KryonOS GitHub Repository.
1. Constructor
new WebSocket(url, protocols)
Creates a new WebSocket connection instance.
- Parameters:
url(String): WebSocket target endpoint (e.g."wss://broker.kryonos.harislab.tech/ws").protocols(StringorArray, optional): Sub-protocol string or array of strings.
- Returns:
WebSocketinstance.
2. Properties & State Constants
| Constant | Value | Description |
|---|---|---|
WebSocket.CONNECTING | 0 | The connection has not yet been established |
WebSocket.OPEN | 1 | The connection is established and communication is possible |
WebSocket.CLOSING | 2 | The connection is undergoing the closing handshake |
WebSocket.CLOSED | 3 | The connection has been closed or could not be opened |
ws.readyState(Integer): Current numeric state.ws.url(String): Connection URL string.
3. Event Callbacks
Assign JavaScript handler functions to the instance event hooks:
ws.onopen = function() { ... }: Triggered when the socket completes its handshake.ws.onmessage = function(event) { ... }: Triggered upon incoming frame reception (event.datacontains string or TypedArray).ws.onerror = function(error) { ... }: Triggered on connection errors.ws.onclose = function(event) { ... }: Triggered on socket disconnection (event.code,event.reason).
4. Methods
ws.send(data)
Transmits text or binary data across the active connection.
- Parameters:
data(String,ArrayBuffer, orUint8Array) - Returns:
Boolean(trueif buffered/transmitted).
ws.close(code, reason)
Initiates a graceful closing handshake.
- Parameters:
code(Integer, optional): Close code (default1000for Normal Closure).reason(String, optional): Short closing message.
- Returns:
undefined
Code Example: Real-Time Telemetry Streamer
// Connect to remote WebSocket broker
var ws = new WebSocket("wss://echo.websocket.events");
ws.onopen = function() {
System.print("WebSocket connected successfully!");
// Send device handshake
ws.send(JSON.stringify({
event: "device_ready",
uptime: System.millis(),
heap: System.getInfo().freeRAM
}));
};
ws.onmessage = function(event) {
System.print("Received message: " + event.data);
try {
var cmd = JSON.parse(event.data);
if (cmd.action === "reboot") {
System.restart();
}
} catch(e) {}
};
ws.onerror = function(err) {
System.print("WebSocket error occurred: " + err);
};
ws.onclose = function(evt) {
System.print("WebSocket closed (code " + evt.code + ")");
};