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