summaryrefslogtreecommitdiffstats
path: root/ipfs-api/examples/ping_peer.rs
blob: 2934c16ce5175a03b51b3dc3e4d156b21a275cbb (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright 2017 rust-ipfs-api Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//

use futures::{future, TryStreamExt};
use ipfs_api::{response::PingResponse, IpfsClient};

// Creates an Ipfs client, discovers a connected peer, and pings it using the
// streaming Api, and by collecting it into a collection.
//
#[cfg_attr(feature = "actix", actix_rt::main)]
#[cfg_attr(feature = "hyper", tokio::main)]
async fn main() {
    eprintln!("connecting to localhost:5001...");

    let client = IpfsClient::default();

    eprintln!();
    eprintln!("discovering connected peers...");

    let peer = match client.swarm_peers().await {
        Ok(connected) => connected
            .peers
            .into_iter()
            .next()
            .expect("expected at least one peer"),
        Err(e) => {
            eprintln!("error getting connected peers: {}", e);
            return;
        }
    };

    eprintln!();
    eprintln!("discovered peer ({})", peer.peer);
    eprintln!();
    eprintln!("streaming 10 pings...");

    if let Err(e) = client
        .ping(&peer.peer[..], Some(10))
        .try_for_each(|ping| {
            eprintln!("{:?}", ping);

            future::ok(())
        })
        .await
    {
        eprintln!("error streaming pings: {}", e);
    }

    eprintln!();
    eprintln!("gathering 15 pings...");

    match client
        .ping(&peer.peer[..], Some(15))
        .try_collect::<Vec<PingResponse>>()
        .await
    {
        Ok(pings) => {
            for ping in pings.iter() {
                eprintln!("got response ({:?}) at ({})...", ping.text, ping.time);
            }
        }
        Err(e) => eprintln!("error collecting pings: {}", e),
    }
}