From a16e45446efc64f00bae7c85780e4a20535ad291 Mon Sep 17 00:00:00 2001 From: Miraculous Owonubi Date: Wed, 8 May 2024 19:18:11 +0300 Subject: [PATCH] add `peers` command --- examples/dcutr/Cargo.toml | 7 ++++++- examples/dcutr/src/main.rs | 31 +++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/examples/dcutr/Cargo.toml b/examples/dcutr/Cargo.toml index 4bb57b0..8b93359 100644 --- a/examples/dcutr/Cargo.toml +++ b/examples/dcutr/Cargo.toml @@ -29,7 +29,12 @@ libp2p = { version = "0.53.2", features = [ multiaddr = "0.18.1" serde = "1.0.196" serde_json = "1.0.113" -tokio = { version = "1.35.1", features = ["macros", "rt", "rt-multi-thread"] } +tokio = { version = "1.35.1", features = [ + "io-std", + "macros", + "rt", + "rt-multi-thread", +] } toml = "0.8.9" tracing = "0.1.37" tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } diff --git a/examples/dcutr/src/main.rs b/examples/dcutr/src/main.rs index a23629e..b905304 100644 --- a/examples/dcutr/src/main.rs +++ b/examples/dcutr/src/main.rs @@ -6,6 +6,7 @@ use futures::{executor::block_on, future::FutureExt, stream::StreamExt}; use libp2p::swarm::{NetworkBehaviour, SwarmEvent}; use libp2p::{dcutr, identify, identity, noise, ping, relay, yamux, Multiaddr, PeerId}; use multiaddr::Protocol; +use tokio::io::AsyncBufReadExt; use tracing::info; use tracing_subscriber::prelude::*; use tracing_subscriber::EnvFilter; @@ -173,8 +174,25 @@ async fn main() -> Result<(), Box> { } block_on(async { + let mut stdin = tokio::io::BufReader::new(tokio::io::stdin()).lines(); + loop { - match swarm.next().await.unwrap() { + let event = tokio::select! { + Some(event) = swarm.next() => event, + Ok(Some(line)) = stdin.next_line() => { + match line.trim() { + "peers" => { + for peer in swarm.connected_peers() { + info!(peer=%peer, "Connected peer"); + } + } + _ => info!("Unknown command"), + } + continue; + } + }; + + match event { SwarmEvent::NewListenAddr { address, .. } => { info!(%address, "Listening on address"); } @@ -185,13 +203,13 @@ async fn main() -> Result<(), Box> { info!("Relay accepted our reservation request"); } SwarmEvent::Behaviour(BehaviourEvent::RelayClient(event)) => { - info!(?event) + info!(?event, "\x1b[33mrelay\x1b[0m"); } SwarmEvent::Behaviour(BehaviourEvent::Dcutr(event)) => { - info!(?event) + info!(?event, "\x1b[32mdcutr\x1b[0m"); } SwarmEvent::Behaviour(BehaviourEvent::Identify(event)) => { - info!(?event) + info!(?event, "\x1b[34midentify\x1b[0m"); } SwarmEvent::Behaviour(BehaviourEvent::Ping(_)) => {} SwarmEvent::ConnectionEstablished { @@ -199,6 +217,11 @@ async fn main() -> Result<(), Box> { } => { info!(peer=%peer_id, ?endpoint, "Established new connection"); } + SwarmEvent::ConnectionClosed { + peer_id, endpoint, .. + } => { + info!(peer=%peer_id, ?endpoint, "Closed connection"); + } SwarmEvent::OutgoingConnectionError { peer_id, error, .. } => { info!(peer=?peer_id, "Outgoing connection failed: {error}"); }