Skip to content

Commit

Permalink
doc(rumqttc): Add separate pub and sub examples
Browse files Browse the repository at this point in the history
  • Loading branch information
mnpw committed Dec 28, 2022
1 parent e0624c1 commit f402da8
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
48 changes: 48 additions & 0 deletions rumqttc/examples/basic-publisher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use tokio::{task, time};

use rumqttc::{self, AsyncClient, Event, MqttOptions, Outgoing, Packet, QoS};
use std::error::Error;
use std::time::Duration;

#[tokio::main(worker_threads = 1)]
async fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
// color_backtrace::install();

let mut mqttoptions = MqttOptions::new("basic-publisher", "localhost", 1884);
mqttoptions.set_keep_alive(Duration::from_secs(5));

let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
task::spawn(async move {
requests(client).await;
time::sleep(Duration::from_secs(3)).await;
});

let mut i = 0;
loop {
let event = eventloop.poll().await;
match event.unwrap() {
Event::Incoming(Packet::PubAck(packet)) => {
println!("[{i}] Incoming puback: {:?}", packet);
}
Event::Outgoing(Outgoing::Publish(packet)) => {
i += 1;
println!("[{i}] Outgoing publish: {:?}", packet);
}
_ => continue,
}
}
}

async fn requests(client: AsyncClient) {
for _ in 1..=10 {
client
.publish("hello/world", QoS::AtLeastOnce, false, vec![1; 1024])
.await
.unwrap();

time::sleep(Duration::from_secs(3)).await;
}

time::sleep(Duration::from_secs(120)).await;
}
42 changes: 42 additions & 0 deletions rumqttc/examples/basic-subscriber.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use tokio::{task, time};

use rumqttc::{self, AsyncClient, Event, MqttOptions, Packet, QoS};
use std::error::Error;
use std::time::Duration;

#[tokio::main(worker_threads = 1)]
async fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
// color_backtrace::install();

let mut mqttoptions = MqttOptions::new("basic-subscriber", "localhost", 1884);
mqttoptions.set_keep_alive(Duration::from_secs(5));

let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
task::spawn(async move {
requests(client).await;
time::sleep(Duration::from_secs(3)).await;
});

let mut i = 0;
loop {
let event = eventloop.poll().await;
match event.unwrap() {
Event::Incoming(Packet::Publish(packet)) => {
i += 1;
println!("[{i}] Incoming publish: {:?}", packet);
}
Event::Incoming(e) => {
println!(" Incoming event: {:?}", e);
}
_ => continue,
}
}
}

async fn requests(client: AsyncClient) {
client
.subscribe("hello/world", QoS::AtMostOnce)
.await
.unwrap();
}

0 comments on commit f402da8

Please sign in to comment.