rendezvous_example/
main.rs1#![doc = include_str!("../README.md")]
22
23use std::{error::Error, time::Duration};
24
25use futures::StreamExt;
26use libp2p::{
27 identify, noise, ping, rendezvous,
28 swarm::{NetworkBehaviour, SwarmEvent},
29 tcp, yamux,
30};
31use tracing_subscriber::EnvFilter;
32
33#[tokio::main]
34async fn main() -> Result<(), Box<dyn Error>> {
35 let _ = tracing_subscriber::fmt()
36 .with_env_filter(EnvFilter::from_default_env())
37 .try_init();
38
39 let keypair = libp2p::identity::Keypair::ed25519_from_bytes([0; 32]).unwrap();
42
43 let mut swarm = libp2p::SwarmBuilder::with_existing_identity(keypair)
44 .with_tokio()
45 .with_tcp(
46 tcp::Config::default(),
47 noise::Config::new,
48 yamux::Config::default,
49 )?
50 .with_behaviour(|key| MyBehaviour {
51 identify: identify::Behaviour::new(identify::Config::new(
52 "rendezvous-example/1.0.0".to_string(),
53 key.public(),
54 )),
55 rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()),
56 ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
57 })?
58 .build();
59
60 let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/62649".parse().unwrap());
61
62 while let Some(event) = swarm.next().await {
63 match event {
64 SwarmEvent::ConnectionEstablished { peer_id, .. } => {
65 tracing::info!("Connected to {}", peer_id);
66 }
67 SwarmEvent::ConnectionClosed { peer_id, .. } => {
68 tracing::info!("Disconnected from {}", peer_id);
69 }
70 SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
71 rendezvous::server::Event::PeerRegistered { peer, registration },
72 )) => {
73 tracing::info!(
74 "Peer {} registered for namespace '{}'",
75 peer,
76 registration.namespace
77 );
78 }
79 SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
80 rendezvous::server::Event::DiscoverServed {
81 enquirer,
82 registrations,
83 },
84 )) => {
85 tracing::info!(
86 "Served peer {} with {} registrations",
87 enquirer,
88 registrations.len()
89 );
90 }
91 other => {
92 tracing::debug!("Unhandled {:?}", other);
93 }
94 }
95 }
96
97 Ok(())
98}
99
100#[derive(NetworkBehaviour)]
101struct MyBehaviour {
102 identify: identify::Behaviour,
103 rendezvous: rendezvous::server::Behaviour,
104 ping: ping::Behaviour,
105}