Skip to main content

pubsub/
pubsub.rs

1use psrt::DEFAULT_PRIORITY;
2use psrt::client::{Client, Config};
3use std::time::Duration;
4use tokio::time::sleep;
5
6#[tokio::main]
7async fn main() {
8    let test_topic = "test/topic1";
9    // define client configuration
10    let config = Config::new("localhost:2873")
11        .set_timeout(Duration::from_secs(5))
12        .build();
13    // connect PSRT client
14    let mut client = Client::connect(&config).await.expect("Failed to connect");
15    // subscribe to the topic
16    client.subscribe(test_topic.to_owned()).await.unwrap();
17    // get data channel
18    let data_channel = client.take_data_channel().unwrap();
19    let receiver_fut = tokio::spawn(async move {
20        // receive messages from the server
21        while let Ok(message) = data_channel.recv().await {
22            println!(
23                "topic: {}, data: {}",
24                message.topic(),
25                message.data_as_str().unwrap()
26            );
27        }
28    });
29    for _ in 0..3 {
30        // if required, check that the client is still connected
31        assert!(client.is_connected());
32        // publish a message
33        client
34            .publish(
35                DEFAULT_PRIORITY,
36                test_topic.to_owned(),
37                "hello".as_bytes().to_vec(),
38            )
39            .await
40            .unwrap();
41        sleep(Duration::from_secs(1)).await;
42    }
43    client.bye().await.unwrap();
44    receiver_fut.await.unwrap();
45}