示例代码
use rumqttc::{AsyncClient, Event, Incoming, MqttOptions, QoS};
use std::time::Duration;
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut mqttoptions = MqttOptions::new("actix_mqtt_gateway", "127.0.0.1", 1883);
mqttoptions.set_keep_alive(Duration::from_secs(30));
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
// 启动 eventloop 在后台处理连接和 ACK
tokio::spawn(async move {
loop {
match eventloop.poll().await {
Ok(Event::Incoming(Incoming::ConnAck(_))) => {
println!(" Connected");
}
Ok(_) => {}
Err(e) => {
eprintln!("MQTT error: {}", e);
break;
}
}
}
});
// 等待连接建立(重要!)
tokio::time::sleep(Duration::from_millis(300)).await;
// 发布消息
client
.publish("test/topic", QoS::AtLeastOnce, false, "Hello from Rust!")
.await?; // 这里的.await同样重要,因为异步client发送的publish是一个future,并不会默认执行,只有当这个 Future 被 .await(或通过其他方式轮询)时,代码才会真正运行
println!("Message sent");
// 必须等待足够时间让消息被发送并确认(尤其 QoS 1/2) tokio::time::sleep(Duration::from_secs(1)).await;
// 现在可以安全退出
Ok(())
}小知识点
在 Rust 的异步世界中:
调用一个 async fn 不会立即执行函数体
它只是构造一个 Future 对象,描述“将来要做什么”
只有当这个 Future 被 .await(或通过其他方式轮询)时,代码才会真正运行


Comments | NOTHING