1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-26 10:41:01 +02:00

Use expect() for error handling in task.md (#1639)

The use of conditionals for error handling makes the code look mode
complex than is.

Read the actual port number from the listener instead of hardcoding port
6142 in two places. That also demonstrates how to deal with ephemeral
ports.

---------

Co-authored-by: Dustin J. Mitchell <dustin@v.igoro.us>
This commit is contained in:
Pavel Roskin
2024-01-03 14:09:50 -08:00
committed by GitHub
parent 3d5bec524f
commit 4e43ddc4d1

View File

@ -13,8 +13,8 @@ use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:6142").await?;
println!("listening on port 6142");
let listener = TcpListener::bind("127.0.0.1:0").await?;
println!("listening on port {}", listener.local_addr()?.port());
loop {
let (mut socket, addr) = listener.accept().await?;
@ -22,26 +22,13 @@ async fn main() -> io::Result<()> {
println!("connection from {addr:?}");
tokio::spawn(async move {
if let Err(e) = socket.write_all(b"Who are you?\n").await {
println!("socket error: {e:?}");
return;
}
socket.write_all(b"Who are you?\n").await.expect("socket error");
let mut buf = vec![0; 1024];
let reply = match socket.read(&mut buf).await {
Ok(n) => {
let name = std::str::from_utf8(&buf[..n]).unwrap().trim();
format!("Thanks for dialing in, {name}!\n")
}
Err(e) => {
println!("socket error: {e:?}");
return;
}
};
if let Err(e) = socket.write_all(reply.as_bytes()).await {
println!("socket error: {e:?}");
}
let name_size = socket.read(&mut buf).await.expect("socket error");
let name = std::str::from_utf8(&buf[..name_size]).unwrap().trim();
let reply = format!("Thanks for dialing in, {name}!\n");
socket.write_all(reply.as_bytes()).await.expect("socket error");
});
}
}