From da55e83e3bed041ff3eb3778b06c7420609aa393 Mon Sep 17 00:00:00 2001 From: Milo Turner Date: Sat, 7 Mar 2020 15:42:24 -0500 Subject: [PATCH] tokio UDP port open in hptp-recv --- Cargo.lock | 3 +-- hptp-recv/Cargo.toml | 4 +++- hptp-recv/src/main.rs | 32 ++++++++++++++++++++++++++++++-- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7261445..3b89e0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -96,6 +96,7 @@ dependencies = [ name = "hptp-recv" version = "0.1.0" dependencies = [ + "failure", "hptp", "tokio", ] @@ -104,9 +105,7 @@ dependencies = [ name = "hptp-send" version = "0.1.0" dependencies = [ - "failure", "hptp", - "tokio", ] [[package]] diff --git a/hptp-recv/Cargo.toml b/hptp-recv/Cargo.toml index 35313af..57b7e1a 100644 --- a/hptp-recv/Cargo.toml +++ b/hptp-recv/Cargo.toml @@ -8,4 +8,6 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -hptp = { path = "../hptp" } \ No newline at end of file +hptp = { path = "../hptp" } +tokio = {version = "0.2.*", features = ["rt-core", "io-std", "io-util", "udp"]} +failure = "0.1.7" diff --git a/hptp-recv/src/main.rs b/hptp-recv/src/main.rs index 1d2e115..706b6b8 100644 --- a/hptp-recv/src/main.rs +++ b/hptp-recv/src/main.rs @@ -1,5 +1,33 @@ +extern crate failure; extern crate hptp; +extern crate tokio; -fn main() { - println!("{}", hptp::RECV_GREETING); +use failure::Error; +use hptp::log::Logger; +use std::net::Ipv4Addr; +use tokio::net::UdpSocket; + +fn main() -> Result<(), Box> { + let mut rt = tokio::runtime::Runtime::new()?; + let mut log = Logger::new(); + let fut = start(&mut log); + Ok(rt.block_on(fut)?) +} + +async fn start(log: &mut Logger) -> Result<(), Error> { + let host = (Ipv4Addr::LOCALHOST, 3700); + let sock = UdpSocket::bind(host).await?; + + log.bound(sock.local_addr()?.port()).await?; + + let (mut rx, _tx) = sock.split(); + let mut buf = [0u8; 2000]; + loop { + let (n, _who) = rx.recv_from(&mut buf).await?; + log.debug_msg(match String::from_utf8(buf[..n].into()) { + Ok(s) => format!("got: {:?}", s), + Err(e) => format!("got: {:?} (invalid utf8)", e.as_bytes()), + }) + .await?; + } }