From 4061fc9fe801cf84bdfcdde10f4c62fa57563e12 Mon Sep 17 00:00:00 2001 From: Alex Auvolat Date: Wed, 2 Dec 2020 21:21:42 +0100 Subject: Complete basalt example --- examples/basalt.rs | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/basalt.rs b/examples/basalt.rs index d6ce520..e09f627 100644 --- a/examples/basalt.rs +++ b/examples/basalt.rs @@ -2,15 +2,18 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use log::info; +use log::{info, warn}; use structopt::StructOpt; +use serde::{Deserialize, Serialize}; use sodiumoxide::crypto::auth; use sodiumoxide::crypto::sign::ed25519; use netapp::NetApp; use netapp::peering::basalt::*; +use netapp::message::*; +use netapp::proto::*; #[derive(StructOpt, Debug)] #[structopt(name = "netapp")] @@ -88,20 +91,56 @@ async fn main() { }; let peering = Basalt::new(netapp.clone(), bootstrap_peers, basalt_params); + netapp.add_msg_handler::( + |_from: ed25519::PublicKey, msg: ExampleMessage| { + info!("Got example message: {:?}, sending example response", msg); + async { + ExampleResponse{example_field: false} + } + } + ); + tokio::join!( - sampling_loop(peering.clone()), + sampling_loop(netapp.clone(), peering.clone()), netapp.listen(), peering.run(), ); } -async fn sampling_loop(basalt: Arc) { + + +async fn sampling_loop(netapp: Arc, basalt: Arc) { loop { tokio::time::delay_for(Duration::from_secs(10)).await; let peers = basalt.sample(10); for p in peers { info!("Sampled: {}", hex::encode(p)); + + let netapp2 = netapp.clone(); + tokio::spawn(async move { + match netapp2.request(&p, ExampleMessage{ + example_field: 42, + }, PRIO_NORMAL).await { + Ok(resp) => info!("Got example response: {:?}", resp), + Err(e) => warn!("Error with example request: {}", e), + } + }); } } } + +#[derive(Serialize, Deserialize, Debug)] +struct ExampleMessage { + example_field: usize, +} + +#[derive(Serialize, Deserialize, Debug)] +struct ExampleResponse { + example_field: bool, +} + +impl Message for ExampleMessage { + const KIND: MessageKind = 0x99000001; + type Response = ExampleResponse; +} -- cgit v1.2.3