client
pub fn client(endpoint string) WsClient用途
客户端。
参数
endpointstring- endpoint(string)
返回值
WsClient — 该类型的值
#github.com/xulang-org/packages/websocket扩展包 `websocket #github.com/xulang-org/packages/websocket`,由模块 github.com/xulang-org/packages 提供。
github.com/xulang-org/packages · 1.17.2 · 安装与使用
以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。
47_standalone_websocket/main.xu@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]")
}clientpub fn client(endpoint string) WsClient客户端。
endpoint stringWsClient — 该类型的值
poolpub fn pool(endpoint string, max_conns int) WsPool执行 pool 处理。
endpoint stringmax_conns intWsPool — 该类型的值
struct WsClientpub struct WsClient {
pub host string
pub port int
pub path string
pub secure bool
}Websocket 客户端会话实例,维护与服务端的连接并提供操作接口。
host stringport intpath stringsecure boolnew_clientpub fn new_client(endpoint string) WsClient构造 client。
endpoint stringWsClient — 该类型的值
(WsClient) connect_securepub fn (c WsClient) connect_secure() transport.ConnWsClient 上的操作:执行 connect secure 操作。失败时抛出错误,调用方需处理或继续传播。
c WsClientWsClient 实例;按值接收。transport.Conn — 该类型的值
(WsClient) send_text_securepub fn (c WsClient) send_text_secure(tc $&transport.Conn, text string) boolWsClient 上的操作:执行 send text secure 操作。
c WsClientWsClient 实例;按值接收。tc $&transport.Conntext stringbool — 是否成立
(WsClient) send_pong_securepub fn (c WsClient) send_pong_secure(tc $&transport.Conn, payload string) boolWsClient 上的操作:执行 send pong secure 操作。
c WsClientWsClient 实例;按值接收。tc $&transport.Connpayload stringbool — 是否成立
(WsClient) read_frame_securepub fn (c WsClient) read_frame_secure(tc $&transport.Conn) FrameWsClient 上的操作:执行 read frame secure 操作。失败时抛出错误,调用方需处理或继续传播。
c WsClientWsClient 实例;按值接收。tc $&transport.ConnFrame — 该类型的值
(WsClient) read_text_securepub fn (c WsClient) read_text_secure(tc $&transport.Conn) stringWsClient 上的操作:执行 read text secure 操作。失败时抛出错误,调用方需处理或继续传播。
c WsClientWsClient 实例;按值接收。tc $&transport.Connstring — 结果字符串
(WsClient) close_securepub fn (c WsClient) close_secure(tc $&transport.Conn)WsClient 上的操作:执行 close secure 操作。
c WsClientWsClient 实例;按值接收。tc $&transport.Conn不返回值。
(WsClient) connectpub fn (c WsClient) connect() int建立与目标服务端点的网络通信连接。失败时抛出错误,调用方需处理或继续传播。
c WsClientWsClient 实例;按值接收。int — 该类型的值
(WsClient) send_textpub fn (c WsClient) send_text(fd int, text string) boolWsClient 上的操作:执行 send text 操作。
c WsClientWsClient 实例;按值接收。fd inttext stringbool — 是否成立
(WsClient) send_binarypub fn (c WsClient) send_binary(fd int, data string) boolWsClient 上的操作:执行 send binary 操作。
c WsClientWsClient 实例;按值接收。fd intdata stringbool — 是否成立
(WsClient) send_pingpub fn (c WsClient) send_ping(fd int, payload string) boolWsClient 上的操作:执行 send ping 操作。
c WsClientWsClient 实例;按值接收。fd intpayload stringbool — 是否成立
(WsClient) send_pongpub fn (c WsClient) send_pong(fd int, payload string) boolWsClient 上的操作:执行 send pong 操作。
c WsClientWsClient 实例;按值接收。fd intpayload stringbool — 是否成立
(WsClient) close_connpub fn (c WsClient) close_conn(fd int)WsClient 上的操作:关闭连接。
c WsClientWsClient 实例;按值接收。fd int不返回值。
(WsClient) read_framepub fn (c WsClient) read_frame(fd int) FrameWsClient 上的操作:执行 read frame 操作。失败时抛出错误,调用方需处理或继续传播。
c WsClientWsClient 实例;按值接收。fd intFrame — 该类型的值
(WsClient) read_textpub fn (c WsClient) read_text(fd int) stringWsClient 上的操作:读取文本。失败时抛出错误,调用方需处理或继续传播。
c WsClientWsClient 实例;按值接收。fd intstring — 结果字符串
const OPCODE_CONTINUATIONpub const OPCODE_CONTINUATION = 0常量 OPCODE_CONTINUATION,定义了相关的协议或算法配置参数。
const OPCODE_TEXTpub const OPCODE_TEXT = 1常量 OPCODE_TEXT,定义了相关的协议或算法配置参数。
const OPCODE_BINARYpub const OPCODE_BINARY = 2常量 OPCODE_BINARY,定义了相关的协议或算法配置参数。
const OPCODE_CLOSEpub const OPCODE_CLOSE = 8常量 OPCODE_CLOSE,定义了相关的协议或算法配置参数。
const OPCODE_PINGpub const OPCODE_PING = 9常量 OPCODE_PING,定义了相关的协议或算法配置参数。
const OPCODE_PONGpub const OPCODE_PONG = 10常量 OPCODE_PONG,定义了相关的协议或算法配置参数。
struct Framepub struct Frame {
pub fin bool
pub opcode int
pub masked bool
pub payload string
}Websocket 协议数据帧结构封装。
fin boolopcode intmasked boolpayload stringbuild_framepub fn build_frame(opcode int, payload string, fin bool, mask bool) string执行 build frame 操作。
opcode intpayload stringfin boolmask boolstring — 结果字符串
apply_maskpub fn apply_mask(payload string, m0 int, m1 int, m2 int, m3 int) string执行 apply mask 操作。
payload stringm0 intm1 intm2 intm3 intstring — 结果字符串
compute_accept_keypub fn compute_accept_key(sec_key string) string执行 compute accept key 操作。
sec_key stringstring — 结果字符串
build_handshake_requestpub fn build_handshake_request(host string, port int, path string, sec_key string) string执行 build handshake request 操作。
host stringport intpath stringsec_key stringstring — 结果字符串
struct HandshakeResultpub struct HandshakeResult {
pub status_code int
pub accept_key string
}承载 status_code、accept_key 等属性的结构体。
status_code intaccept_key stringparse_handshake_responsepub fn parse_handshake_response(resp string) HandshakeResult解析为 handshake response。
resp stringHandshakeResult — 该类型的值
struct WsPoolpub struct WsPool {
pub client WsClient
pub idle chan int
pub max_idle int
}Websocket 连接池管理器,并发安全地维护和调度复用套接字连接。
client WsClientidle chan intmax_idle intopen_poolpub fn open_pool(endpoint string, max_idle int) WsPool执行 open pool 操作。
endpoint stringmax_idle intWsPool — 该类型的值
(&WsPool) get_connpub fn (p &WsPool) get_conn() int&WsPool 上的操作:读取 conn。
p &WsPoolWsPool 实例;以只读借用传入,调用方仍持有实例。int — 该类型的值
(&WsPool) put_connpub fn (p &WsPool) put_conn(fd int)&WsPool 上的操作:执行 put conn 操作。
p &WsPoolWsPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&WsPool) echo_textpub fn (p &WsPool) echo_text(text string) string&WsPool 上的操作:执行 echo text 操作。失败时抛出错误,调用方需处理或继续传播。
p &WsPoolWsPool 实例;以只读借用传入,调用方仍持有实例。text stringstring — 结果字符串
(&WsPool) closepub fn (p &WsPool) close()&WsPool 上的操作:关闭资源。
p &WsPoolWsPool 实例;以只读借用传入,调用方仍持有实例。不返回值。