client
pub fn client(endpoint string) WsClientPurpose
Execute client.
Parameters
endpointstring- endpoint (string)
Returns
WsClient — a value of this type
#github.com/xulang-org/packages/websocketExternal 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
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@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) WsClientExecute client.
endpoint stringWsClient — a value of this type
poolpub fn pool(endpoint string, max_conns int) WsPoolExecute pool.
endpoint stringmax_conns intWsPool — a value of this type
struct WsClientpub struct WsClient {
pub host string
pub port int
pub path string
pub secure bool
}Websocket Client session maintaining connection and operations.
host stringport intpath stringsecure boolnew_clientpub fn new_client(endpoint string) WsClientConstruct client.
endpoint stringWsClient — a value of this type
(WsClient) connect_securepub fn (c WsClient) connect_secure() transport.ConnOperation on WsClient: connect secure. Throws on failure; handle the error or propagate it to the caller.
c WsClientWsClient instance used by this call (value receiver).transport.Conn — a value of this type
(WsClient) send_text_securepub fn (c WsClient) send_text_secure(tc $&transport.Conn, text string) boolOperation on WsClient: send text secure.
c WsClientWsClient instance used by this call (value receiver).tc $&transport.Conntext stringbool — true or false
(WsClient) send_pong_securepub fn (c WsClient) send_pong_secure(tc $&transport.Conn, payload string) boolOperation on WsClient: send pong secure.
c WsClientWsClient instance used by this call (value receiver).tc $&transport.Connpayload stringbool — true or false
(WsClient) read_frame_securepub fn (c WsClient) read_frame_secure(tc $&transport.Conn) FrameOperation on WsClient: read frame secure. Throws on failure; handle the error or propagate it to the caller.
c WsClientWsClient instance used by this call (value receiver).tc $&transport.ConnFrame — a value of this type
(WsClient) read_text_securepub fn (c WsClient) read_text_secure(tc $&transport.Conn) stringOperation on WsClient: read text secure. Throws on failure; handle the error or propagate it to the caller.
c WsClientWsClient instance used by this call (value receiver).tc $&transport.Connstring — result string
(WsClient) close_securepub fn (c WsClient) close_secure(tc $&transport.Conn)Operation on WsClient: close secure.
c WsClientWsClient instance used by this call (value receiver).tc $&transport.ConnThis call does not return a value.
(WsClient) connectpub fn (c WsClient) connect() intEstablish network connection to the target server endpoint. Throws on failure; handle the error or propagate it to the caller.
c WsClientWsClient instance used by this call (value receiver).int — a value of this type
(WsClient) send_textpub fn (c WsClient) send_text(fd int, text string) boolOperation on WsClient: send text.
c WsClientWsClient instance used by this call (value receiver).fd inttext stringbool — true or false
(WsClient) send_binarypub fn (c WsClient) send_binary(fd int, data string) boolOperation on WsClient: send binary.
c WsClientWsClient instance used by this call (value receiver).fd intdata stringbool — true or false
(WsClient) send_pingpub fn (c WsClient) send_ping(fd int, payload string) boolOperation on WsClient: send ping.
c WsClientWsClient instance used by this call (value receiver).fd intpayload stringbool — true or false
(WsClient) send_pongpub fn (c WsClient) send_pong(fd int, payload string) boolOperation on WsClient: send pong.
c WsClientWsClient instance used by this call (value receiver).fd intpayload stringbool — true or false
(WsClient) close_connpub fn (c WsClient) close_conn(fd int)Operation on WsClient: close connection.
c WsClientWsClient instance used by this call (value receiver).fd intThis call does not return a value.
(WsClient) read_framepub fn (c WsClient) read_frame(fd int) FrameOperation on WsClient: read frame. Throws on failure; handle the error or propagate it to the caller.
c WsClientWsClient instance used by this call (value receiver).fd intFrame — a value of this type
(WsClient) read_textpub fn (c WsClient) read_text(fd int) stringOperation on WsClient: read text. Throws on failure; handle the error or propagate it to the caller.
c WsClientWsClient instance used by this call (value receiver).fd intstring — result string
const OPCODE_CONTINUATIONpub const OPCODE_CONTINUATION = 0Constant OPCODE_CONTINUATION, defining protocol or algorithm parameters.
const OPCODE_TEXTpub const OPCODE_TEXT = 1Constant OPCODE_TEXT, defining protocol or algorithm parameters.
const OPCODE_BINARYpub const OPCODE_BINARY = 2Constant OPCODE_BINARY, defining protocol or algorithm parameters.
const OPCODE_CLOSEpub const OPCODE_CLOSE = 8Constant OPCODE_CLOSE, defining protocol or algorithm parameters.
const OPCODE_PINGpub const OPCODE_PING = 9Constant OPCODE_PING, defining protocol or algorithm parameters.
const OPCODE_PONGpub const OPCODE_PONG = 10Constant OPCODE_PONG, defining protocol or algorithm parameters.
struct Framepub struct Frame {
pub fin bool
pub opcode int
pub masked bool
pub payload string
}Websocket Protocol data frame encapsulation.
fin boolopcode intmasked boolpayload stringbuild_framepub fn build_frame(opcode int, payload string, fin bool, mask bool) stringBuilds a WebSocket frame according to RFC 6455
opcode intpayload stringfin boolmask boolstring — result string
apply_maskpub fn apply_mask(payload string, m0 int, m1 int, m2 int, m3 int) stringUnmasks or masks payload given 4-byte mask
payload stringm0 intm1 intm2 intm3 intstring — result string
compute_accept_keypub fn compute_accept_key(sec_key string) stringCompute accept key.
sec_key stringstring — result string
build_handshake_requestpub fn build_handshake_request(host string, port int, path string, sec_key string) stringBuild handshake request.
host stringport intpath stringsec_key stringstring — result string
struct HandshakeResultpub struct HandshakeResult {
pub status_code int
pub accept_key string
}Structure encapsulating status_code, accept_key.
status_code intaccept_key stringparse_handshake_responsepub fn parse_handshake_response(resp string) HandshakeResultParse as handshake response.
resp stringHandshakeResult — a value of this type
struct WsPoolpub struct WsPool {
pub client WsClient
pub idle chan int
pub max_idle int
}Websocket Connection pool manager scheduling reusable socket connections.
client WsClientidle chan intmax_idle intopen_poolpub fn open_pool(endpoint string, max_idle int) WsPoolOpen pool.
endpoint stringmax_idle intWsPool — a value of this type
(&WsPool) get_connpub fn (p &WsPool) get_conn() intOperation on &WsPool: read conn.
p &WsPoolWsPool instance used by this call (borrow).int — a value of this type
(&WsPool) put_connpub fn (p &WsPool) put_conn(fd int)Operation on &WsPool: put connection.
p &WsPoolWsPool instance used by this call (borrow).fd intThis call does not return a value.
(&WsPool) echo_textpub fn (p &WsPool) echo_text(text string) stringExecutes an echo round-trip borrowing from pool Throws on failure; handle the error or propagate it to the caller.
p &WsPoolWsPool instance used by this call (borrow).text stringstring — result string
(&WsPool) closepub fn (p &WsPool) close()Operation on &WsPool: close the resource.
p &WsPoolWsPool instance used by this call (borrow).This call does not return a value.