XU XUv0.16.0

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

导入方式: websocket #github.com/xulang-org/packages/websocket

公开 API: 9 函数, 18 方法, 4 类型, 6 常量, 0 方法集

扩展包 `websocket #github.com/xulang-org/packages/websocket`,由模块 github.com/xulang-org/packages 提供。

github.com/xulang-org/packages · 1.17.2 · 安装与使用

示例代码 · API 声明

示例代码

以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。

47_standalone_websocket/main.xu

所需 SDK:Xu 0.10.5 · 完整工程 · 下载源码

Xu本地 SDK 示例
@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 声明

client

XuAPI
pub fn client(endpoint string) WsClient

用途

客户端。

参数

endpoint string
endpoint(string)

返回值

WsClient — 该类型的值

pool

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

用途

执行 pool 处理。

参数

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

返回值

WsPool — 该类型的值

struct WsClient

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

用途

Websocket 客户端会话实例,维护与服务端的连接并提供操作接口。

公开字段

host string
主机
port int
端口
path string
文件系统路径
secure bool
字段(bool)

查看用法示例

new_client

XuAPI
pub fn new_client(endpoint string) WsClient

用途

构造 client。

参数

endpoint string
endpoint(string)

返回值

WsClient — 该类型的值

(WsClient) connect_secure

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

用途

WsClient 上的操作:执行 connect secure 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。

返回值

transport.Conn — 该类型的值

(WsClient) send_text_secure

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

用途

WsClient 上的操作:执行 send text secure 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
tc $&transport.Conn
tc(独占借用,可修改原值;类型 $&transport.Conn)
text string
文本(string)

返回值

bool — 是否成立

(WsClient) send_pong_secure

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

用途

WsClient 上的操作:执行 send pong secure 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
tc $&transport.Conn
tc(独占借用,可修改原值;类型 $&transport.Conn)
payload string
payload(string)

返回值

bool — 是否成立

(WsClient) read_frame_secure

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

用途

WsClient 上的操作:执行 read frame secure 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
tc $&transport.Conn
tc(独占借用,可修改原值;类型 $&transport.Conn)

返回值

Frame — 该类型的值

(WsClient) read_text_secure

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

用途

WsClient 上的操作:执行 read text secure 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
tc $&transport.Conn
tc(独占借用,可修改原值;类型 $&transport.Conn)

返回值

string — 结果字符串

(WsClient) close_secure

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

用途

WsClient 上的操作:执行 close secure 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
tc $&transport.Conn
tc(独占借用,可修改原值;类型 $&transport.Conn)

返回值

不返回值。

(WsClient) connect

XuAPI
pub fn (c WsClient) connect() int

用途

建立与目标服务端点的网络通信连接。失败时抛出错误,调用方需处理或继续传播。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。

返回值

int — 该类型的值

(WsClient) send_text

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

用途

WsClient 上的操作:执行 send text 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)
text string
文本(string)

返回值

bool — 是否成立

(WsClient) send_binary

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

用途

WsClient 上的操作:执行 send binary 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)
data string
数据(string)

返回值

bool — 是否成立

(WsClient) send_ping

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

用途

WsClient 上的操作:执行 send ping 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)
payload string
payload(string)

返回值

bool — 是否成立

(WsClient) send_pong

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

用途

WsClient 上的操作:执行 send pong 操作。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)
payload string
payload(string)

返回值

bool — 是否成立

(WsClient) close_conn

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

用途

WsClient 上的操作:关闭连接。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)

返回值

不返回值。

(WsClient) read_frame

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

用途

WsClient 上的操作:执行 read frame 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)

返回值

Frame — 该类型的值

(WsClient) read_text

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

用途

WsClient 上的操作:读取文本。失败时抛出错误,调用方需处理或继续传播。

参数

c WsClient
本次调用使用的 WsClient 实例;按值接收。
fd int
文件描述符(int)

返回值

string — 结果字符串

const OPCODE_CONTINUATION

XuAPI
pub const OPCODE_CONTINUATION = 0

用途

常量 OPCODE_CONTINUATION,定义了相关的协议或算法配置参数。

const OPCODE_TEXT

XuAPI
pub const OPCODE_TEXT = 1

用途

常量 OPCODE_TEXT,定义了相关的协议或算法配置参数。

查看用法示例

const OPCODE_BINARY

XuAPI
pub const OPCODE_BINARY = 2

用途

常量 OPCODE_BINARY,定义了相关的协议或算法配置参数。

const OPCODE_CLOSE

XuAPI
pub const OPCODE_CLOSE = 8

用途

常量 OPCODE_CLOSE,定义了相关的协议或算法配置参数。

const OPCODE_PING

XuAPI
pub const OPCODE_PING = 9

用途

常量 OPCODE_PING,定义了相关的协议或算法配置参数。

const OPCODE_PONG

XuAPI
pub const OPCODE_PONG = 10

用途

常量 OPCODE_PONG,定义了相关的协议或算法配置参数。

struct Frame

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

用途

Websocket 协议数据帧结构封装。

公开字段

fin bool
字段(bool)
opcode int
字段(int)
masked bool
字段(bool)
payload string
字段(string)

build_frame

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

用途

执行 build frame 操作。

参数

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

返回值

string — 结果字符串

查看用法示例

apply_mask

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

用途

执行 apply mask 操作。

参数

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

返回值

string — 结果字符串

查看用法示例

compute_accept_key

XuAPI
pub fn compute_accept_key(sec_key string) string

用途

执行 compute accept key 操作。

参数

sec_key string
sec_key(string)

返回值

string — 结果字符串

查看用法示例

build_handshake_request

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

用途

执行 build handshake request 操作。

参数

host string
主机(string)
port int
端口(int)
path string
文件系统路径(string)
sec_key string
sec_key(string)

返回值

string — 结果字符串

struct HandshakeResult

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

用途

承载 status_code、accept_key 等属性的结构体。

公开字段

status_code int
字段(int)
accept_key string
字段(string)

parse_handshake_response

XuAPI
pub fn parse_handshake_response(resp string) HandshakeResult

用途

解析为 handshake response。

参数

resp string
resp(string)

返回值

HandshakeResult — 该类型的值

struct WsPool

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

用途

Websocket 连接池管理器,并发安全地维护和调度复用套接字连接。

公开字段

client WsClient
字段(WsClient)
idle chan int
字段(通道;类型 chan int)
max_idle int
字段(int)

查看用法示例

open_pool

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

用途

执行 open pool 操作。

参数

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

返回值

WsPool — 该类型的值

查看用法示例

(&WsPool) get_conn

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

用途

&WsPool 上的操作:读取 conn。

参数

p &WsPool
本次调用使用的 WsPool 实例;以只读借用传入,调用方仍持有实例。

返回值

int — 该类型的值

(&WsPool) put_conn

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

用途

&WsPool 上的操作:执行 put conn 操作。

参数

p &WsPool
本次调用使用的 WsPool 实例;以只读借用传入,调用方仍持有实例。
fd int
文件描述符(int)

返回值

不返回值。

(&WsPool) echo_text

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

用途

&WsPool 上的操作:执行 echo text 操作。失败时抛出错误,调用方需处理或继续传播。

参数

p &WsPool
本次调用使用的 WsPool 实例;以只读借用传入,调用方仍持有实例。
text string
文本(string)

返回值

string — 结果字符串

(&WsPool) close

XuAPI
pub fn (p &WsPool) close()

用途

&WsPool 上的操作:关闭资源。

参数

p &WsPool
本次调用使用的 WsPool 实例;以只读借用传入,调用方仍持有实例。

返回值

不返回值。