ADd client and README

This commit is contained in:
Bastian Gruber 2023-05-01 12:10:43 +02:00
parent cda9d2e2a3
commit 1b4d5f0eef
No known key found for this signature in database
GPG key ID: BE9F8C772B188CBF
3 changed files with 75 additions and 3 deletions

32
problem_04/README.md Normal file
View file

@ -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
```

View file

@ -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<dyn Error>> {
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
println!("Usage: {} <server-ip:port> <request>", 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(())
}

View file

@ -1,3 +0,0 @@
fn main() {
println!("Hello, world!");
}