open
pub fn open(addr string) ClientPurpose
Open resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
Parameters
addrstring- address (string)
Returns
Client — a value of this type
#github.com/xulang-org/packages/natsNATS high-performance cloud-native messaging driver for Xu. Features Standard NATS text protocol implementation in 100% pure Xu. High-throughput publish/subscribe (PUB/SUB). Queue Groups (distributed load-balanced worker queues). Request-Reply RPC pattern with dynamic inbox routing. Automatic PING/PONG heartbeat management.
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.
24_standalone_nats/main.xu@main
nats #github.com/xulang-org/packages/nats
#os
fn main() int {
println("=== NATS Cloud-Native Messaging Standalone Integration Test ===")
addr := "127.0.0.1:4222"
println("Connecting to NATS at " + addr + "...")
$nc := nats.connect(addr + "") >>> (err) {
println("Connection to NATS failed: " + err.msg())
<< 1
}
ping_ok := nc.ping() >>> (err) {
println("Ping failed: " + err.msg())
<< 1
}
println("1. NATS Ping response: " + str(ping_ok))
// 2. Subscribe to subject
topic := "xu.events"
sub := nc.subscribe(topic + "") >>> (err) {
println("Subscribe failed: " + err.msg())
<< 1
}
println("2. Subscribed to subject: " + sub.subject + " (sid=" + sub.sid + ")")
// 3. Publish a message
payload := "Hello NATS from Xu Programming Language!"
nc.publish(topic + "", payload + "") >>> (err) {
println("Publish failed: " + err.msg())
<< 1
}
println("3. Published payload: " + payload)
// 4. Receive the message
msg := nc.next_msg() >>> (err) {
println("Receive failed: " + err.msg())
<< 1
}
println("4. Successfully received message:")
println(" - Subject: " + msg.subject)
println(" - Sid: " + msg.sid)
println(" - Data: " + msg.data)
// 5. Test Queue Group (load-balanced worker queue)
q_sub := nc.queue_subscribe("xu.tasks", "workers") >>> (err) {
println("Queue subscribe failed: " + err.msg())
<< 1
}
println("5. Queue Group subscribed: xu.tasks -> workers (sid=" + q_sub.sid + ")")
nc.publish("xu.tasks", "task_payload_123") >>> (err) {
<< 1
}
q_msg := nc.next_msg() >>> (err) {
<< 1
}
println("6. Queue Group received task: " + q_msg.data)
nc.unsubscribe(sub) >>> (err) {
<< 1
}
nc.unsubscribe(q_sub) >>> (err) {
<< 1
}
nc.close()
// 7. NATS Connection Pool Deep Verification
println("7. Testing NATS Connection Pool with Reuse & Concurrency...")
pool := nats.open_pool("127.0.0.1:4222", 5)
$c1 := pool.get() >>> (err) {
println("Pool get c1 failed: " + err.msg())
<< 1
}
fd_first := c1.fd
c1_ok := c1.ping() >>> (err) {
<< 1
}
println(" Pool c1 ping: " + str(c1_ok) + " (fd=" + str(fd_first) + ")")
pool.put(c1)
// Verify Pool Connection REUSE
$c2 := pool.get() >>> (err) {
println("Pool get c2 failed: " + err.msg())
<< 1
}
fd_second := c2.fd
if fd_first == fd_second {
println(" [PASS] NATS Pool Connection REUSE verified! (fd1 == fd2: " + str(fd_first) + ")")
} else {
println(" [WARN] fd1 != fd2 (fd1=" + str(fd_first) + ", fd2=" + str(fd_second) + ")")
}
// Concurrent borrow another connection
$c3 := pool.get() >>> (err) {
println("Pool get c3 failed: " + err.msg())
<< 1
}
fd_third := c3.fd
if fd_second != fd_third {
println(" [PASS] NATS Pool Multi-connection concurrency verified! (fd2=" + str(fd_second) + " != fd3=" + str(fd_third) + ")")
}
// Pool Direct Publish
pool.publish("pool.notify", "notification from nats pool") >>> (err) {
<< 1
}
println(" [PASS] NATS Pool direct publish succeeded.")
pool.put(c2)
pool.put(c3)
pool.close()
println(" [PASS] NATS Pool closed cleanly.")
println("=== NATS Tests Completed Successfully! ===")
<< 0
}openpub fn open(addr string) ClientOpen resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
addr stringClient — a value of this type
open_poolpub fn open_pool(addr string, max_idle int) PoolOpen pool.
addr stringmax_idle intPool — a value of this type
struct Clientpub struct Client {
pub fd int
pub buf string
pub addr string
pub next_sid int
pub server_info string
}Nats Client session maintaining connection and operations.
fd intbuf stringaddr stringnext_sid intserver_info string($&Client) read_linepub fn (c $&Client) read_line() stringOperation on $&Client: read line. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).string — result string
($&Client) read_bytespub fn (c $&Client) read_bytes(n int) stringOperation on $&Client: read through delim (inclusive). Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).n intstring — result string
($&Client) write_rawpub fn (c $&Client) write_raw(data string) intOperation on $&Client: write raw. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).data stringint — a value of this type
connectpub fn connect(addr string) ClientExecute connect.
addr stringClient — a value of this type
connect_authpub fn connect_auth(addr string, user string, pass string) ClientConnect auth. Throws on failure; handle the error or propagate it to the caller.
addr stringuser stringpass stringClient — a value of this type
($&Client) pingpub fn (c $&Client) ping() boolSend a ping heartbeat request to verify connection liveness. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).bool — true or false
($&Client) publishpub fn (c $&Client) publish(subject string, data string) intPublish message data to the given topic or channel. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).subject stringdata stringint — a value of this type
($&Client) publish_requestpub fn (c $&Client) publish_request(subject string, reply_to string, data string) intOperation on $&Client: publish request. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).subject stringreply_to stringdata stringint — a value of this type
($&Client) subscribepub fn (c $&Client) subscribe(subject string) SubscriptionExecute subscribe on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).subject stringSubscription — a value of this type
($&Client) queue_subscribepub fn (c $&Client) queue_subscribe(subject string, queue_group string) SubscriptionOperation on $&Client: queue subscribe. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).subject stringqueue_group stringSubscription — a value of this type
($&Client) unsubscribepub fn (c $&Client) unsubscribe(sub Subscription) intExecute unsubscribe on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).sub Subscriptionint — a value of this type
($&Client) next_msgpub fn (c $&Client) next_msg() MessageOperation on $&Client: next msg. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).Message — a value of this type
($&Client) requestpub fn (c $&Client) request(subject string, data string) MessageExecute request on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).subject stringdata stringMessage — a value of this type
($&Client) closepub fn (c $&Client) close() intOperation on $&Client: close the resource.
c $&ClientClient instance used by this call (exclusive borrow).int — a value of this type
struct Messagepub struct Message {
pub subject string
pub sid string
pub reply_to string
pub data string
}Structure encapsulating subject, sid, reply_to, data.
subject stringsid stringreply_to stringdata stringnew_msgpub fn new_msg(subject string, sid string, reply_to string, data string) MessageConstruct msg.
subject stringsid stringreply_to stringdata stringMessage — a value of this type
struct Poolpub struct Pool {
pub url string
pub auth_user string
pub auth_pass string
pub idle chan int
pub max_idle int
}Connection Pool for NATS messaging system. Uses channel of socket file descriptors for lightweight and high-throughput pooling.
url stringauth_user stringauth_pass stringidle chan intmax_idle intnew_poolpub fn new_pool(url string, max_idle int) PoolConstruct pool.
url stringmax_idle intPool — a value of this type
new_pool_authpub fn new_pool_auth(url string, user string, pass string, max_idle int) PoolConstruct pool auth.
url stringuser stringpass stringmax_idle intPool — a value of this type
(&Pool) getpub fn (p &Pool) get() ClientExecute get on &Pool. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).Client — a value of this type
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)Operation on &Pool: put connection.
p &PoolPool instance used by this call (borrow).fd intThis call does not return a value.
(&Pool) putpub fn (p &Pool) put(c Client)Store or update the value associated with the specified key.
p &PoolPool instance used by this call (borrow).c ClientThis call does not return a value.
(&Pool) publishpub fn (p &Pool) publish(subject string, data string) intPublish message data to the given topic or channel. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).subject stringdata stringint — a value of this type
(&Pool) closepub fn (p &Pool) close()Operation on &Pool: close the resource.
p &PoolPool instance used by this call (borrow).This call does not return a value.
struct Subscriptionpub struct Subscription {
pub sid string
pub subject string
pub queue_group string
}Structure encapsulating sid, subject, queue_group.
sid stringsubject stringqueue_group stringnew_subpub fn new_sub(sid string, subject string, queue_group string) SubscriptionConstruct sub.
sid stringsubject stringqueue_group stringSubscription — a value of this type
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Nats Client session maintaining connection and operations.
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClientTls connect. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intTlsClient — a value of this type
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClientTls connect config. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intcfg tls.ConfigTlsClient — a value of this type
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) intOperation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).data stringint — a value of this type
($&TlsClient) readpub fn (c $&TlsClient) read(max int) stringOperation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).max intstring — result string
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) stringOperation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).need intstring — result string
($&TlsClient) closepub fn (c $&TlsClient) close() intOperation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).int — a value of this type
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) intOperation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) intOperation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) intOperation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type