use bytes::Bytes;
use color_eyre::eyre::Result;
use qp2p::{Endpoint, WireMsg};
use std::{
env,
net::{Ipv4Addr, SocketAddr},
};
#[derive(Default, Ord, PartialEq, PartialOrd, Eq, Clone, Copy)]
struct XId(pub [u8; 32]);
#[tokio::main]
async fn main() -> Result<()> {
color_eyre::install()?;
const MSG_MARCO: &str = "marco";
const MSG_POLO: &str = "polo";
let args: Vec<String> = env::args().collect();
let (node, mut incoming_conns) = Endpoint::builder()
.addr((Ipv4Addr::LOCALHOST, 0))
.idle_timeout(60 * 60 * 1_000 )
.server()?;
if args.len() > 1 {
for arg in args.iter().skip(1) {
let peer: SocketAddr = arg
.parse()
.expect("Invalid SocketAddr. Use the form 127.0.0.1:1234");
let msg = Bytes::from(MSG_MARCO);
println!("Sending to {peer:?} --> {msg:?}\n");
let (conn, mut incoming) = node.connect_to(&peer).await?;
conn.send((Bytes::new(), Bytes::new(), msg.clone())).await?;
let reply = incoming.next().await.unwrap();
println!("Received from {peer:?} --> {reply:?}");
}
println!("Done sending");
}
println!("\n---");
println!("Listening on: {:?}", node.local_addr());
println!("---\n");
while let Some((connection, mut incoming)) = incoming_conns.next().await {
let src = connection.remote_address();
while let Ok(Some(WireMsg((_, _, bytes)))) = incoming.next().await {
println!("Received from {src:?} --> {bytes:?}");
if bytes == *MSG_MARCO {
let reply = Bytes::from(MSG_POLO);
connection
.send((Bytes::new(), Bytes::new(), reply.clone()))
.await?;
println!("Replied to {src:?} --> {reply:?}");
}
println!();
}
}
Ok(())
}