Skip to content

Commit 4e43ddc

Browse files
proskidjmitche
andauthored
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 <[email protected]>
1 parent 3d5bec5 commit 4e43ddc

File tree

1 file changed

+7
-20
lines changed

1 file changed

+7
-20
lines changed

src/async/tasks.md

+7-20
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,22 @@ use tokio::net::TcpListener;
1313
1414
#[tokio::main]
1515
async fn main() -> io::Result<()> {
16-
let listener = TcpListener::bind("127.0.0.1:6142").await?;
17-
println!("listening on port 6142");
16+
let listener = TcpListener::bind("127.0.0.1:0").await?;
17+
println!("listening on port {}", listener.local_addr()?.port());
1818
1919
loop {
2020
let (mut socket, addr) = listener.accept().await?;
2121
2222
println!("connection from {addr:?}");
2323
2424
tokio::spawn(async move {
25-
if let Err(e) = socket.write_all(b"Who are you?\n").await {
26-
println!("socket error: {e:?}");
27-
return;
28-
}
25+
socket.write_all(b"Who are you?\n").await.expect("socket error");
2926
3027
let mut buf = vec![0; 1024];
31-
let reply = match socket.read(&mut buf).await {
32-
Ok(n) => {
33-
let name = std::str::from_utf8(&buf[..n]).unwrap().trim();
34-
format!("Thanks for dialing in, {name}!\n")
35-
}
36-
Err(e) => {
37-
println!("socket error: {e:?}");
38-
return;
39-
}
40-
};
41-
42-
if let Err(e) = socket.write_all(reply.as_bytes()).await {
43-
println!("socket error: {e:?}");
44-
}
28+
let name_size = socket.read(&mut buf).await.expect("socket error");
29+
let name = std::str::from_utf8(&buf[..name_size]).unwrap().trim();
30+
let reply = format!("Thanks for dialing in, {name}!\n");
31+
socket.write_all(reply.as_bytes()).await.expect("socket error");
4532
});
4633
}
4734
}

0 commit comments

Comments
 (0)