XU XUv0.16.0

#github.com/xulang-org/packages/websocket

import: websocket #github.com/xulang-org/packages/websocket

counts: 9 functions, 18 methods, 4 types, 6 constants, 0 method sets

External package `websocket #github.com/xulang-org/packages/websocket`, provided by github.com/xulang-org/packages.

github.com/xulang-org/packages · 1.17.2 · Install and use

Examples · API declarations

Examples

These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.

47_standalone_websocket/main.xu

Required SDK: Xu 0.10.5 · Complete project · Download source

XuLocal SDK example
@main

websocket #github.com/xulang-org/packages/websocket
#errors
#strings

fn verify_rfc_handshake_and_framing() {
    println("--- 1. Testing RFC 6455 Handshake & Frame Masking ---")

    // RFC 6455 Section 1.3 example
    sec_key := "dGhlIHNhbXBsZSBub25jZQ=="
    accept := websocket.compute_accept_key(sec_key)
    expected_accept := "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
    if accept == expected_accept {
        println("   [PASS] RFC 6455 Sec-WebSocket-Accept calculation: " + accept)
    } else {
        println("   [FAIL] Expected " + expected_accept + ", got " + accept)
    }

    // Masking test
    plain := "WebSocket Mask Test"
    masked := websocket.apply_mask(plain + "", 0x11, 0x22, 0x33, 0x44)
    unmasked := websocket.apply_mask(masked + "", 0x11, 0x22, 0x33, 0x44)
    if unmasked == plain {
        println("   [PASS] 4-byte XOR Masking & Unmasking matched cleanly.")
    } else {
        println("   [FAIL] Masking round-trip failed!")
    }

    // Build frame test
    frame_bytes := websocket.build_frame(websocket.OPCODE_TEXT, "Hello", true, true)
    // 2 bytes hdr + 4 bytes mask + 5 bytes payload = 11 bytes
    if frame_bytes.len == 11 {
        println("   [PASS] Masked Frame length verified: 11 bytes")
    } else {
        println("   [FAIL] Unexpected frame length: " + str(frame_bytes.len))
    }
}

fn ws_coro_worker(id int, host string, port int, idle chan int, done chan int) {
    p := websocket.WsPool{
        client: websocket.WsClient{host: host, port: port, path: "/", secure: false},
        idle: idle,
        max_idle: 5
    }
    msg := "ws_coro_msg_" + str(id)
    echoed := p.echo_text(msg + "") >>> (err) {
        println("   [FAIL] ws worker " + str(id) + " echo failed: " + err.msg())
        done <- -id
        <<
    }
    if echoed == msg {
        println("   [PASS] xu ws worker " + str(id) + " echo round-trip succeeded: " + echoed)
        done <- id
    } else {
        println("   [FAIL] ws worker " + str(id) + " echo mismatch")
        done <- -id
    }
}

fn verify_ws_pool_and_echo() {
    println("\n--- 2. Testing WebSocket Connection Pool & Echo ---")
    $p := websocket.open_pool("ws://127.0.0.1:8080", 5)

    // 1. Connection Reuse
    fd1 := p.get_conn()
    if fd1 < 0 {
        println("   [FAIL] Failed to connect")
        <<
    }
    println("   Borrow 1 fd: " + str(fd1))
    p.put_conn(fd1)

    fd2 := p.get_conn()
    if fd2 < 0 {
        println("   [FAIL] Failed to re-borrow")
        <<
    }
    println("   Borrow 2 (after return) fd: " + str(fd2))
    if fd1 == fd2 {
        println("   [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
    } else {
        println("   [WARN] Different fd: " + str(fd1) + " vs " + str(fd2))
    }

    // 2. Concurrency
    fd3 := p.get_conn()
    if fd3 < 0 {
        println("   [FAIL] Failed to borrow concurrent")
        <<
    }
    println("   Borrow 3 (concurrently) fd: " + str(fd3))
    if fd2 != fd3 {
        println("   [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
    } else {
        println("   [FAIL] Expected distinct fds for concurrent connections!")
    }
    p.put_conn(fd2)
    p.put_conn(fd3)

    // 3. Pool Echo round-trip
    test_msg := "Hello Xu WebSocket 2026!"
    echoed := p.echo_text(test_msg + "") >>> (err) {
        println("   [FAIL] Pool echo failed: " + err.msg())
        p.close()
        <<
    }
    if echoed == test_msg {
        println("   [PASS] Echo round-trip matched exactly: '" + echoed + "'")
    } else {
        println("   [FAIL] Echo mismatch: expected '" + test_msg + "', got '" + echoed + "'")
    }

    // 4. Testing Pool with Real 'xu' Coroutines
    println("\n   Testing WebSocket Pool with Real 'xu' Coroutines...")
    done_ch := chan int{cap: 10}
    xu ws_coro_worker(1, p.client.host + "", p.client.port, p.idle, done_ch)
    xu ws_coro_worker(2, p.client.host + "", p.client.port, p.idle, done_ch)
    xu ws_coro_worker(3, p.client.host + "", p.client.port, p.idle, done_ch)
    xu ws_coro_worker(4, p.client.host + "", p.client.port, p.idle, done_ch)

    $completed_ws := 0
    for w in 0:4 {
        res_id := <-done_ch
        if res_id > 0 {
            completed_ws = completed_ws + 1
        }
    }
    println("   [PASS] All " + str(completed_ws) + " concurrent 'xu' WebSocket coroutines completed via Pool!")

    p.close()
    println("   [PASS] WebSocket Pool closed cleanly.")
}

fn main() {
    println("=== Xu WebSocket Native Driver Verification ===\n")
    verify_rfc_handshake_and_framing()
    verify_ws_pool_and_echo()
    println("\n[WEBSOCKET VERIFICATION 100% COMPLETED]")
}

API declarations

client

XuAPI
pub fn client(endpoint string) WsClient

Purpose

Execute client.

Parameters

endpoint string
endpoint (string)

Returns

WsClient — a value of this type

pool

XuAPI
pub fn pool(endpoint string, max_conns int) WsPool

Purpose

Execute pool.

Parameters

endpoint string
endpoint (string)
max_conns int
max_conns (int)

Returns

WsPool — a value of this type

struct WsClient

XuAPI
pub struct WsClient {
    pub host string
    pub port int
    pub path string
    pub secure bool
}

Purpose

Websocket Client session maintaining connection and operations.

Public fields

host string
host
port int
port
path string
filesystem path
secure bool
field (bool)

See usage example

new_client

XuAPI
pub fn new_client(endpoint string) WsClient

Purpose

Construct client.

Parameters

endpoint string
endpoint (string)

Returns

WsClient — a value of this type

(WsClient) connect_secure

XuAPI
pub fn (c WsClient) connect_secure() transport.Conn

Purpose

Operation on WsClient: connect secure. Throws on failure; handle the error or propagate it to the caller.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).

Returns

transport.Conn — a value of this type

(WsClient) send_text_secure

XuAPI
pub fn (c WsClient) send_text_secure(tc $&transport.Conn, text string) bool

Purpose

Operation on WsClient: send text secure.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
tc $&transport.Conn
tc (exclusive borrow; may modify the original; type $&transport.Conn)
text string
text (string)

Returns

bool — true or false

(WsClient) send_pong_secure

XuAPI
pub fn (c WsClient) send_pong_secure(tc $&transport.Conn, payload string) bool

Purpose

Operation on WsClient: send pong secure.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
tc $&transport.Conn
tc (exclusive borrow; may modify the original; type $&transport.Conn)
payload string
payload (string)

Returns

bool — true or false

(WsClient) read_frame_secure

XuAPI
pub fn (c WsClient) read_frame_secure(tc $&transport.Conn) Frame

Purpose

Operation on WsClient: read frame secure. Throws on failure; handle the error or propagate it to the caller.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
tc $&transport.Conn
tc (exclusive borrow; may modify the original; type $&transport.Conn)

Returns

Frame — a value of this type

(WsClient) read_text_secure

XuAPI
pub fn (c WsClient) read_text_secure(tc $&transport.Conn) string

Purpose

Operation on WsClient: read text secure. Throws on failure; handle the error or propagate it to the caller.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
tc $&transport.Conn
tc (exclusive borrow; may modify the original; type $&transport.Conn)

Returns

string — result string

(WsClient) close_secure

XuAPI
pub fn (c WsClient) close_secure(tc $&transport.Conn)

Purpose

Operation on WsClient: close secure.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
tc $&transport.Conn
tc (exclusive borrow; may modify the original; type $&transport.Conn)

Returns

This call does not return a value.

(WsClient) connect

XuAPI
pub fn (c WsClient) connect() int

Purpose

Establish network connection to the target server endpoint. Throws on failure; handle the error or propagate it to the caller.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).

Returns

int — a value of this type

(WsClient) send_text

XuAPI
pub fn (c WsClient) send_text(fd int, text string) bool

Purpose

Operation on WsClient: send text.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)
text string
text (string)

Returns

bool — true or false

(WsClient) send_binary

XuAPI
pub fn (c WsClient) send_binary(fd int, data string) bool

Purpose

Operation on WsClient: send binary.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)
data string
data (string)

Returns

bool — true or false

(WsClient) send_ping

XuAPI
pub fn (c WsClient) send_ping(fd int, payload string) bool

Purpose

Operation on WsClient: send ping.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)
payload string
payload (string)

Returns

bool — true or false

(WsClient) send_pong

XuAPI
pub fn (c WsClient) send_pong(fd int, payload string) bool

Purpose

Operation on WsClient: send pong.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)
payload string
payload (string)

Returns

bool — true or false

(WsClient) close_conn

XuAPI
pub fn (c WsClient) close_conn(fd int)

Purpose

Operation on WsClient: close connection.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)

Returns

This call does not return a value.

(WsClient) read_frame

XuAPI
pub fn (c WsClient) read_frame(fd int) Frame

Purpose

Operation on WsClient: read frame. Throws on failure; handle the error or propagate it to the caller.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)

Returns

Frame — a value of this type

(WsClient) read_text

XuAPI
pub fn (c WsClient) read_text(fd int) string

Purpose

Operation on WsClient: read text. Throws on failure; handle the error or propagate it to the caller.

Parameters

c WsClient
The WsClient instance used by this call (value receiver).
fd int
file descriptor (int)

Returns

string — result string

const OPCODE_CONTINUATION

XuAPI
pub const OPCODE_CONTINUATION = 0

Purpose

Constant OPCODE_CONTINUATION, defining protocol or algorithm parameters.

const OPCODE_TEXT

XuAPI
pub const OPCODE_TEXT = 1

Purpose

Constant OPCODE_TEXT, defining protocol or algorithm parameters.

See usage example

const OPCODE_BINARY

XuAPI
pub const OPCODE_BINARY = 2

Purpose

Constant OPCODE_BINARY, defining protocol or algorithm parameters.

const OPCODE_CLOSE

XuAPI
pub const OPCODE_CLOSE = 8

Purpose

Constant OPCODE_CLOSE, defining protocol or algorithm parameters.

const OPCODE_PING

XuAPI
pub const OPCODE_PING = 9

Purpose

Constant OPCODE_PING, defining protocol or algorithm parameters.

const OPCODE_PONG

XuAPI
pub const OPCODE_PONG = 10

Purpose

Constant OPCODE_PONG, defining protocol or algorithm parameters.

struct Frame

XuAPI
pub struct Frame {
    pub fin bool
    pub opcode int
    pub masked bool
    pub payload string
}

Purpose

Websocket Protocol data frame encapsulation.

Public fields

fin bool
field (bool)
opcode int
field (int)
masked bool
field (bool)
payload string
field (string)

build_frame

XuAPI
pub fn build_frame(opcode int, payload string, fin bool, mask bool) string

Purpose

Builds a WebSocket frame according to RFC 6455

Parameters

opcode int
opcode (int)
payload string
payload (string)
fin bool
fin (bool)
mask bool
mask (bool)

Returns

string — result string

See usage example

apply_mask

XuAPI
pub fn apply_mask(payload string, m0 int, m1 int, m2 int, m3 int) string

Purpose

Unmasks or masks payload given 4-byte mask

Parameters

payload string
payload (string)
m0 int
m0 (int)
m1 int
m1 (int)
m2 int
m2 (int)
m3 int
m3 (int)

Returns

string — result string

See usage example

compute_accept_key

XuAPI
pub fn compute_accept_key(sec_key string) string

Purpose

Compute accept key.

Parameters

sec_key string
sec_key (string)

Returns

string — result string

See usage example

build_handshake_request

XuAPI
pub fn build_handshake_request(host string, port int, path string, sec_key string) string

Purpose

Build handshake request.

Parameters

host string
host (string)
port int
port (int)
path string
filesystem path (string)
sec_key string
sec_key (string)

Returns

string — result string

struct HandshakeResult

XuAPI
pub struct HandshakeResult {
    pub status_code int
    pub accept_key string
}

Purpose

Structure encapsulating status_code, accept_key.

Public fields

status_code int
field (int)
accept_key string
field (string)

parse_handshake_response

XuAPI
pub fn parse_handshake_response(resp string) HandshakeResult

Purpose

Parse as handshake response.

Parameters

resp string
resp (string)

Returns

HandshakeResult — a value of this type

struct WsPool

XuAPI
pub struct WsPool {
    pub client WsClient
    pub idle chan int
    pub max_idle int
}

Purpose

Websocket Connection pool manager scheduling reusable socket connections.

Public fields

client WsClient
field (WsClient)
idle chan int
field (channel; type chan int)
max_idle int
field (int)

See usage example

open_pool

XuAPI
pub fn open_pool(endpoint string, max_idle int) WsPool

Purpose

Open pool.

Parameters

endpoint string
endpoint (string)
max_idle int
max_idle (int)

Returns

WsPool — a value of this type

See usage example

(&WsPool) get_conn

XuAPI
pub fn (p &WsPool) get_conn() int

Purpose

Operation on &WsPool: read conn.

Parameters

p &WsPool
The WsPool instance used by this call (borrow).

Returns

int — a value of this type

(&WsPool) put_conn

XuAPI
pub fn (p &WsPool) put_conn(fd int)

Purpose

Operation on &WsPool: put connection.

Parameters

p &WsPool
The WsPool instance used by this call (borrow).
fd int
file descriptor (int)

Returns

This call does not return a value.

(&WsPool) echo_text

XuAPI
pub fn (p &WsPool) echo_text(text string) string

Purpose

Executes an echo round-trip borrowing from pool Throws on failure; handle the error or propagate it to the caller.

Parameters

p &WsPool
The WsPool instance used by this call (borrow).
text string
text (string)

Returns

string — result string

(&WsPool) close

XuAPI
pub fn (p &WsPool) close()

Purpose

Operation on &WsPool: close the resource.

Parameters

p &WsPool
The WsPool instance used by this call (borrow).

Returns

This call does not return a value.