aboutsummaryrefslogtreecommitdiff
path: root/jsonrpc/examples/pubsub_client.rs
blob: fee2a269250e73dd06a942b228b0bb91d8bcba15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use serde::{Deserialize, Serialize};
use smol::stream::StreamExt;

use karyon_jsonrpc::Client;

#[derive(Deserialize, Serialize, Debug)]
struct Pong {}

fn main() {
    env_logger::init();
    smol::future::block_on(async {
        let client = Client::builder("tcp://127.0.0.1:6000")
            .expect("Create client builder")
            .build()
            .await
            .expect("Build a client");

        let result: Pong = client
            .call("Calc.ping", ())
            .await
            .expect("Send ping request");

        println!("receive pong msg: {:?}", result);

        let (sub_id, sub) = client
            .subscribe("Calc.log_subscribe", ())
            .await
            .expect("Subscribe to log_subscribe method");

        smol::spawn(async move {
            sub.for_each(|m| {
                println!("Receive new notification: {m}");
            })
            .await
        })
        .detach();

        smol::Timer::after(std::time::Duration::from_secs(5)).await;

        client
            .unsubscribe("Calc.log_unsubscribe", sub_id)
            .await
            .expect("Unsubscribe from log_unsubscirbe method");

        smol::Timer::after(std::time::Duration::from_secs(2)).await;
    });
}