XU XUv0.16.0

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

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

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

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

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

示例代码 · API 声明

示例代码

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

25_standalone_mqtt/main.xu

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

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

API 声明

open

XuAPI
pub fn open(addr string, client_id string) Client

用途

打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。

参数

addr string
地址(string)
client_id string
client_id(string)

返回值

Client — 该类型的值

查看用法示例

open_pool

XuAPI
pub fn open_pool(addr string, id_prefix string, max_idle int) Pool

用途

执行 open pool 操作。

参数

addr string
地址(string)
id_prefix string
id_prefix(string)
max_idle int
max_idle(int)

返回值

Pool — 该类型的值

查看用法示例

struct Client

XuAPI
pub struct Client {
    pub fd int
    pub addr string
    pub client_id string
    pub next_pid int
}

用途

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

公开字段

fd int
文件描述符
addr string
地址
client_id string
字段(string)
next_pid int
字段(int)

struct Message

XuAPI
pub struct Message {
    pub topic string
    pub payload string
    pub qos int
}

用途

承载 topic、payload、qos 等属性的结构体。

公开字段

topic string
字段(string)
payload string
字段(string)
qos int
字段(int)

connect_opts

XuAPI
pub fn connect_opts(addr string, client_id string, username string, password string, clean_session bool, keepalive int) Client

用途

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

参数

addr string
地址(string)
client_id string
client_id(string)
username string
username(string)
password string
password(string)
clean_session bool
clean_session(bool)
keepalive int
keepalive(int)

返回值

Client — 该类型的值

connect

XuAPI
pub fn connect(addr string, client_id string) Client

用途

执行 connect 处理。失败时抛出错误,调用方需处理或继续传播。

参数

addr string
地址(string)
client_id string
client_id(string)

返回值

Client — 该类型的值

connect_auth

XuAPI
pub fn connect_auth(addr string, client_id string, username string, password string) Client

用途

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

参数

addr string
地址(string)
client_id string
client_id(string)
username string
username(string)
password string
password(string)

返回值

Client — 该类型的值

($&Client) ping

XuAPI
pub fn (c $&Client) ping() bool

用途

发送心跳保活探测请求,检测连接活性与服务可用性。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

bool — 是否成立

($&Client) publish

XuAPI
pub fn (c $&Client) publish(topic string, payload string, qos int) int

用途

向指定的消息主题或频道广播发布消息。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
topic string
topic(string)
payload string
payload(string)
qos int
qos(int)

返回值

int — 该类型的值

($&Client) subscribe

XuAPI
pub fn (c $&Client) subscribe(topic string, qos int) int

用途

在 $&Client 上执行 subscribe 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
topic string
topic(string)
qos int
qos(int)

返回值

int — 该类型的值

($&Client) read_message

XuAPI
pub fn (c $&Client) read_message() Message

用途

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

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

Message — 该类型的值

($&Client) disconnect

XuAPI
pub fn (c $&Client) disconnect() int

用途

在 $&Client 上执行 disconnect 操作。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

int — 该类型的值

($&Client) close

XuAPI
pub fn (c $&Client) close() int

用途

$&Client 上的操作:关闭资源。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

int — 该类型的值

struct Pool

XuAPI
pub struct Pool {
    pub addr string
    pub id_prefix string
    pub idle chan int
    pub max_idle int
    pub seq chan int
}

用途

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

公开字段

addr string
地址
id_prefix string
字段(string)
idle chan int
字段(通道;类型 chan int)
max_idle int
字段(int)
seq chan int
字段(通道;类型 chan int)

new_pool

XuAPI
pub fn new_pool(addr string, id_prefix string, max_idle int) Pool

用途

构造 pool。

参数

addr string
地址(string)
id_prefix string
id_prefix(string)
max_idle int
max_idle(int)

返回值

Pool — 该类型的值

(&Pool) get

XuAPI
pub fn (p &Pool) get() Client

用途

在 &Pool 上执行 get 操作。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

Client — 该类型的值

(&Pool) put_conn

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

用途

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

参数

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

返回值

不返回值。

(&Pool) put

XuAPI
pub fn (p &Pool) put(c Client)

用途

写入或更新指定键对应的值数据。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
c Client
字节或字符码(Client)

返回值

不返回值。

(&Pool) publish

XuAPI
pub fn (p &Pool) publish(topic string, payload string, qos int) int

用途

向指定的消息主题或频道广播发布消息。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
topic string
topic(string)
payload string
payload(string)
qos int
qos(int)

返回值

int — 该类型的值

(&Pool) close

XuAPI
pub fn (p &Pool) close()

用途

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

参数

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

返回值

不返回值。

encode_u16

XuAPI
pub fn encode_u16(n int) string

用途

编码 u16 数据。

参数

n int
数量、长度或上限(int)

返回值

string — 结果字符串

decode_u16

XuAPI
pub fn decode_u16(s &string, off int) int

用途

解码 u16 数据。

参数

s &string
源字符串(只读借用,调用方仍持有原值;类型 &string)
off int
偏移(int)

返回值

int — 该类型的值

encode_str

XuAPI
pub fn encode_str(text string) string

用途

编码 str 数据。

参数

text string
文本(string)

返回值

string — 结果字符串

encode_var_len

XuAPI
pub fn encode_var_len(val int) string

用途

编码 var len 数据。

参数

val int
值(int)

返回值

string — 结果字符串

struct TlsClient

XuAPI
pub struct TlsClient {
    pub conn transport.Conn
    pub host string
    pub port int
}

用途

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

公开字段

conn transport.Conn
字段(transport.Conn)
host string
主机
port int
端口

tls_connect

XuAPI
pub fn tls_connect(endpoint string, default_port int) TlsClient

用途

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

参数

endpoint string
endpoint(string)
default_port int
default_port(int)

返回值

TlsClient — 该类型的值

tls_connect_config

XuAPI
pub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient

用途

执行 tls connect config 操作。失败时抛出错误,调用方需处理或继续传播。

参数

endpoint string
endpoint(string)
default_port int
default_port(int)
cfg tls.Config
cfg(tls.Config)

返回值

TlsClient — 该类型的值

($&TlsClient) write_all

XuAPI
pub fn (c $&TlsClient) write_all(data string) int

用途

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

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
data string
数据(string)

返回值

int — 该类型的值

($&TlsClient) read

XuAPI
pub fn (c $&TlsClient) read(max int) string

用途

$&TlsClient 上的操作:读出最多 max 字节。失败时抛出错误,调用方需处理或继续传播。

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
max int
上限(int)

返回值

string — 结果字符串

($&TlsClient) read_exact

XuAPI
pub fn (c $&TlsClient) read_exact(need int) string

用途

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

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
need int
need(int)

返回值

string — 结果字符串

($&TlsClient) close

XuAPI
pub fn (c $&TlsClient) close() int

用途

$&TlsClient 上的操作:关闭资源。失败时抛出错误,调用方需处理或继续传播。

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

int — 该类型的值

($&TlsClient) set_deadline

XuAPI
pub fn (c $&TlsClient) set_deadline(t_ns int) int

用途

$&TlsClient 上的操作:设置 deadline。失败时抛出错误,调用方需处理或继续传播。

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
t_ns int
t_ns(int)

返回值

int — 该类型的值

($&TlsClient) set_read_deadline

XuAPI
pub fn (c $&TlsClient) set_read_deadline(t_ns int) int

用途

$&TlsClient 上的操作:设置 read deadline。失败时抛出错误,调用方需处理或继续传播。

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
t_ns int
t_ns(int)

返回值

int — 该类型的值

($&TlsClient) set_write_deadline

XuAPI
pub fn (c $&TlsClient) set_write_deadline(t_ns int) int

用途

$&TlsClient 上的操作:设置 write deadline。失败时抛出错误,调用方需处理或继续传播。

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
t_ns int
t_ns(int)

返回值

int — 该类型的值