diff --git a/hptp-send/src/main.rs b/hptp-send/src/main.rs index 2f13df7..4c2f808 100644 --- a/hptp-send/src/main.rs +++ b/hptp-send/src/main.rs @@ -1,53 +1,75 @@ -// #![feature(backtrace)] +#![feature(backtrace)] extern crate hptp; extern crate tokio; #[macro_use] extern crate thiserror; +use hptp::log::Logger; use std::net::SocketAddrV4; #[derive(Error, Debug)] enum Error { + #[error("io error: {source}")] + Io { + #[from] + source: tokio::io::Error, + backtrace: std::backtrace::Backtrace, + }, #[error("invalid command-line arguments")] InvalidArgs, + #[error("did not find an available local port")] + NoAvailPort, } fn main() { match entry() { Err(Error::InvalidArgs) => print_usage(), - /* - Err(e) => { - use std::error::Error; - println!("Error: {:?}", e); - for bt in e.backtrace() { - println!("{}", bt); - } - } - */ + Err(e) => { + use std::error::Error; + println!("Error: {:?}", e); + for bt in e.backtrace() { + println!("{}", bt); + } + } Ok(()) => (), } } fn print_usage() { - print!("usage:\n./3700send :\n") + print!("Usage:\n./3700send :\n") } fn entry() -> Result<(), Error> { let mut rt = tokio::runtime::Runtime::new().unwrap(); - // let mut log = Logger::new(); - rt.block_on(start()) + let mut log = Logger::new(); + rt.block_on(start(&mut log)) } -async fn start() -> Result<(), Error> { - let addr = parse_arg()?; - println!("ip={}, port={}", addr.ip(), addr.port()); +async fn start(log: &mut Logger) -> Result<(), Error> { + let targ_addr = parse_args(std::env::args())?; + let sock = hptp::udp_retrying_bind(16, hptp::random_port) + .await + .map_err(|_| Error::NoAvailPort)?; + log.debug_msg(format!("bound on {}", sock.local_addr()?)) + .await; + upload(log, sock, targ_addr).await?; + log.debug_msg("bye!").await; Ok(()) } -fn parse_arg() -> Result { - std::env::args() - .nth(1) +fn parse_args(mut args: impl Iterator) -> Result { + args.nth(1) .ok_or(Error::InvalidArgs)? .parse() .map_err(|_| Error::InvalidArgs) } + +async fn upload( + _log: &mut Logger, + mut sock: tokio::net::UdpSocket, + targ_addr: SocketAddrV4, +) -> Result<(), Error> { + sock.send_to("Hello, ".as_bytes(), targ_addr).await?; + sock.send_to("world!".as_bytes(), targ_addr).await?; + Ok(()) +}