protohackers/problem_01/src/main.rs

33 lines
940 B
Rust
Raw Normal View History

2023-04-17 19:45:27 +00:00
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:4040").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
loop {
let n = match socket.read(&mut buf).await {
Ok(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
2023-04-18 08:50:02 +00:00
log::error!("failed to read from socket; err = {:?}", e);
2023-04-17 19:45:27 +00:00
return;
}
};
if let Err(e) = socket.write_all(&buf[0..n]).await {
2023-04-18 08:50:02 +00:00
log::error!("failed to write to socket; err = {:?}", e);
2023-04-17 19:45:27 +00:00
return;
}
}
});
}
}