diff --git a/problem_04/README.md b/problem_04/README.md new file mode 100644 index 0000000..66a9739 --- /dev/null +++ b/problem_04/README.md @@ -0,0 +1,32 @@ +## Usage + +### Star the server +```bash +$ cargo run --bin server +``` + +or with logs: + +```bash +$ RUST_LOG=info cargo run --bin server +``` + +### Test with the client + +```bash +$ cargo run --bin client 127.0.0.1:1222 "foo=bar" +``` + +## Example output + +```bash +$ cargo run --bin client 127.0.0.1:1222 "foo=bar" + Finished dev [unoptimized + debuginfo] target(s) in 0.02s + Running `target/debug/client '127.0.0.1:1222' foo=bar` +Insert request sent. No response expected. + +$ cargo run --bin client 127.0.0.1:1222 "foo" + Finished dev [unoptimized + debuginfo] target(s) in 0.02s + Running `target/debug/client '127.0.0.1:1222' foo` +Received response: foo=bar +``` \ No newline at end of file diff --git a/problem_04/bin/client.rs b/problem_04/bin/client.rs index e69de29..830c931 100644 --- a/problem_04/bin/client.rs +++ b/problem_04/bin/client.rs @@ -0,0 +1,43 @@ +use std::env; +use std::error::Error; +use std::net::SocketAddr; +use std::time::Duration; +use tokio::net::UdpSocket; + +const MAX_DATAGRAM_SIZE: usize = 1000; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let args: Vec = env::args().collect(); + + if args.len() < 3 { + println!("Usage: {} ", args[0]); + return Ok(()); + } + + let server_addr: SocketAddr = args[1].parse()?; + let request = args[2].clone(); + + let local_addr = if server_addr.is_ipv4() { + "0.0.0.0:0" + } else { + "[::]:0" + }; + + let socket = UdpSocket::bind(local_addr).await?; + socket.connect(server_addr).await?; + + socket.send(request.as_bytes()).await?; + + if request.contains('=') { + println!("Insert request sent. No response expected."); + } else { + let mut buf = vec![0; MAX_DATAGRAM_SIZE]; + let _ = tokio::time::timeout(Duration::from_secs(1), socket.recv(&mut buf)).await?; + + let response = String::from_utf8_lossy(&buf); + println!("Received response: {}", response); + } + + Ok(()) +} diff --git a/problem_04/src/lib.rs b/problem_04/src/lib.rs deleted file mode 100644 index e7a11a9..0000000 --- a/problem_04/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - println!("Hello, world!"); -}