Skip to content

Commit f402da8

Browse files
committed
doc(rumqttc): Add separate pub and sub examples
1 parent e0624c1 commit f402da8

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

rumqttc/examples/basic-publisher.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use tokio::{task, time};
2+
3+
use rumqttc::{self, AsyncClient, Event, MqttOptions, Outgoing, Packet, QoS};
4+
use std::error::Error;
5+
use std::time::Duration;
6+
7+
#[tokio::main(worker_threads = 1)]
8+
async fn main() -> Result<(), Box<dyn Error>> {
9+
pretty_env_logger::init();
10+
// color_backtrace::install();
11+
12+
let mut mqttoptions = MqttOptions::new("basic-publisher", "localhost", 1884);
13+
mqttoptions.set_keep_alive(Duration::from_secs(5));
14+
15+
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
16+
task::spawn(async move {
17+
requests(client).await;
18+
time::sleep(Duration::from_secs(3)).await;
19+
});
20+
21+
let mut i = 0;
22+
loop {
23+
let event = eventloop.poll().await;
24+
match event.unwrap() {
25+
Event::Incoming(Packet::PubAck(packet)) => {
26+
println!("[{i}] Incoming puback: {:?}", packet);
27+
}
28+
Event::Outgoing(Outgoing::Publish(packet)) => {
29+
i += 1;
30+
println!("[{i}] Outgoing publish: {:?}", packet);
31+
}
32+
_ => continue,
33+
}
34+
}
35+
}
36+
37+
async fn requests(client: AsyncClient) {
38+
for _ in 1..=10 {
39+
client
40+
.publish("hello/world", QoS::AtLeastOnce, false, vec![1; 1024])
41+
.await
42+
.unwrap();
43+
44+
time::sleep(Duration::from_secs(3)).await;
45+
}
46+
47+
time::sleep(Duration::from_secs(120)).await;
48+
}

rumqttc/examples/basic-subscriber.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use tokio::{task, time};
2+
3+
use rumqttc::{self, AsyncClient, Event, MqttOptions, Packet, QoS};
4+
use std::error::Error;
5+
use std::time::Duration;
6+
7+
#[tokio::main(worker_threads = 1)]
8+
async fn main() -> Result<(), Box<dyn Error>> {
9+
pretty_env_logger::init();
10+
// color_backtrace::install();
11+
12+
let mut mqttoptions = MqttOptions::new("basic-subscriber", "localhost", 1884);
13+
mqttoptions.set_keep_alive(Duration::from_secs(5));
14+
15+
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
16+
task::spawn(async move {
17+
requests(client).await;
18+
time::sleep(Duration::from_secs(3)).await;
19+
});
20+
21+
let mut i = 0;
22+
loop {
23+
let event = eventloop.poll().await;
24+
match event.unwrap() {
25+
Event::Incoming(Packet::Publish(packet)) => {
26+
i += 1;
27+
println!("[{i}] Incoming publish: {:?}", packet);
28+
}
29+
Event::Incoming(e) => {
30+
println!(" Incoming event: {:?}", e);
31+
}
32+
_ => continue,
33+
}
34+
}
35+
}
36+
37+
async fn requests(client: AsyncClient) {
38+
client
39+
.subscribe("hello/world", QoS::AtMostOnce)
40+
.await
41+
.unwrap();
42+
}

0 commit comments

Comments
 (0)