open
pub fn open(addr string, client_id string) Client用途
打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。
参数
addrstring- 地址(string)
client_idstring- client_id(string)
返回值
Client — 该类型的值
#github.com/xulang-org/packages/mqtt扩展包 `mqtt #github.com/xulang-org/packages/mqtt`,由模块 github.com/xulang-org/packages 提供。
github.com/xulang-org/packages · 1.17.2 · 安装与使用
以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。
25_standalone_mqtt/main.xu@main
mqtt #github.com/xulang-org/packages/mqtt
#os
fn main() int {
println("=== MQTT 3.1.1 IoT & Messaging Standalone Integration Test ===")
addr := "127.0.0.1:1883"
client_id := "xu_test_node_42"
println("Connecting to MQTT Broker at " + addr + " (client_id=" + client_id + ")...")
$client := mqtt.open(addr + "", client_id + "") >>> (err) {
println("MQTT connect failed: " + err.msg())
<< 1
}
println("1. MQTT Session established successfully (CONNACK code=0).")
// 2. Ping heartbeat
is_alive := client.ping()
println("2. PINGREQ/PINGRESP heartbeat: " + str(is_alive))
// 3. Subscribe
topic := "devices/status"
client.subscribe(topic + "", 0) >>> (err) {
println("Subscribe failed: " + err.msg())
<< 1
}
println("3. Subscribed to topic: " + topic + " (QoS 0)")
// 4. Publish QoS 0
payload_0 := "{\"status\": \"online\", \"battery\": 98}"
client.publish(topic + "", payload_0 + "", 0) >>> (err) {
println("Publish QoS 0 failed: " + err.msg())
<< 1
}
println("4. Published QoS 0 message: " + payload_0)
// 5. Publish QoS 1 (waits for PUBACK)
payload_1 := "{\"critical_alert\": \"temperature threshold exceeded\"}"
client.publish(topic + "", payload_1 + "", 1) >>> (err) {
println("Publish QoS 1 failed: " + err.msg())
<< 1
}
println("5. Published QoS 1 message (received PUBACK confirmation).")
// 6. Disconnect
client.disconnect()
println("6. Gracefully disconnected from Broker.")
// 7. MQTT Connection Pool Deep Verification
println("7. Testing MQTT Connection Pool with Reuse & Concurrency...")
pool := mqtt.open_pool(addr + "", "xu_mqtt_pool", 5)
$c1 := pool.get() >>> (err) {
println("Pool get c1 failed: " + err.msg())
<< 1
}
fd_first := c1.fd
c1_ok := c1.ping()
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] MQTT 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] MQTT Pool Multi-connection concurrency verified! (fd2=" + str(fd_second) + " != fd3=" + str(fd_third) + ")")
}
// Pool Direct Publish
pool.publish("sensors/pool_alert", "temperature=29C", 0) >>> (err) {
<< 1
}
println(" [PASS] MQTT Pool direct publish succeeded.")
pool.put(c2)
pool.put(c3)
pool.close()
println(" [PASS] MQTT Pool closed cleanly.")
println("=== MQTT Tests Completed Successfully! ===")
<< 0
}openpub fn open(addr string, client_id string) Client打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。
addr stringclient_id stringClient — 该类型的值
open_poolpub fn open_pool(addr string, id_prefix string, max_idle int) Pool执行 open pool 操作。
addr stringid_prefix stringmax_idle intPool — 该类型的值
struct Clientpub struct Client {
pub fd int
pub addr string
pub client_id string
pub next_pid int
}Mqtt 客户端会话实例,维护与服务端的连接并提供操作接口。
fd intaddr stringclient_id stringnext_pid intstruct Messagepub struct Message {
pub topic string
pub payload string
pub qos int
}承载 topic、payload、qos 等属性的结构体。
topic stringpayload stringqos intconnect_optspub fn connect_opts(addr string, client_id string, username string, password string, clean_session bool, keepalive int) Client执行 connect opts 操作。失败时抛出错误,调用方需处理或继续传播。
addr stringclient_id stringusername stringpassword stringclean_session boolkeepalive intClient — 该类型的值
connectpub fn connect(addr string, client_id string) Client执行 connect 处理。失败时抛出错误,调用方需处理或继续传播。
addr stringclient_id stringClient — 该类型的值
connect_authpub fn connect_auth(addr string, client_id string, username string, password string) Client执行 connect auth 操作。失败时抛出错误,调用方需处理或继续传播。
addr stringclient_id stringusername stringpassword stringClient — 该类型的值
($&Client) pingpub fn (c $&Client) ping() bool发送心跳保活探测请求,检测连接活性与服务可用性。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。bool — 是否成立
($&Client) publishpub fn (c $&Client) publish(topic string, payload string, qos int) int向指定的消息主题或频道广播发布消息。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。topic stringpayload stringqos intint — 该类型的值
($&Client) subscribepub fn (c $&Client) subscribe(topic string, qos int) int在 $&Client 上执行 subscribe 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。topic stringqos intint — 该类型的值
($&Client) read_messagepub fn (c $&Client) read_message() Message$&Client 上的操作:执行 read message 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。Message — 该类型的值
($&Client) disconnectpub fn (c $&Client) disconnect() int在 $&Client 上执行 disconnect 操作。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。int — 该类型的值
($&Client) closepub fn (c $&Client) close() int$&Client 上的操作:关闭资源。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。int — 该类型的值
struct Poolpub struct Pool {
pub addr string
pub id_prefix string
pub idle chan int
pub max_idle int
pub seq chan int
}Mqtt 连接池管理器,并发安全地维护和调度复用套接字连接。
addr stringid_prefix stringidle chan intmax_idle intseq chan intnew_poolpub fn new_pool(addr string, id_prefix string, max_idle int) Pool构造 pool。
addr stringid_prefix stringmax_idle intPool — 该类型的值
(&Pool) getpub fn (p &Pool) get() Client在 &Pool 上执行 get 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。Client — 该类型的值
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)&Pool 上的操作:执行 put conn 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&Pool) putpub fn (p &Pool) put(c Client)写入或更新指定键对应的值数据。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。c Client不返回值。
(&Pool) publishpub fn (p &Pool) publish(topic string, payload string, qos int) int向指定的消息主题或频道广播发布消息。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。topic stringpayload stringqos intint — 该类型的值
(&Pool) closepub fn (p &Pool) close()&Pool 上的操作:关闭资源。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。不返回值。
encode_u16pub fn encode_u16(n int) string编码 u16 数据。
n intstring — 结果字符串
decode_u16pub fn decode_u16(s &string, off int) int解码 u16 数据。
s &stringoff intint — 该类型的值
encode_strpub fn encode_str(text string) string编码 str 数据。
text stringstring — 结果字符串
encode_var_lenpub fn encode_var_len(val int) string编码 var len 数据。
val intstring — 结果字符串
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Mqtt 客户端会话实例,维护与服务端的连接并提供操作接口。
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClient执行 tls connect 操作。失败时抛出错误,调用方需处理或继续传播。
endpoint stringdefault_port intTlsClient — 该类型的值
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient执行 tls connect config 操作。失败时抛出错误,调用方需处理或继续传播。
endpoint stringdefault_port intcfg tls.ConfigTlsClient — 该类型的值
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) int$&TlsClient 上的操作:执行 write all 操作。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。data stringint — 该类型的值
($&TlsClient) readpub fn (c $&TlsClient) read(max int) string$&TlsClient 上的操作:读出最多 max 字节。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。max intstring — 结果字符串
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) string$&TlsClient 上的操作:执行 read exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。need intstring — 结果字符串
($&TlsClient) closepub fn (c $&TlsClient) close() int$&TlsClient 上的操作:关闭资源。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。int — 该类型的值
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) int$&TlsClient 上的操作:设置 deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) int$&TlsClient 上的操作:设置 read deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) int$&TlsClient 上的操作:设置 write deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值