Skip to content

Commit cd49dcd

Browse files
authored
docs(example): add comments to the examples/hello.rs example (#3150)
1 parent 4cf38a1 commit cd49dcd

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

examples/hello.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ use hyper::service::service_fn;
1010
use hyper::{Request, Response};
1111
use tokio::net::TcpListener;
1212

13+
// An async function that consumes a request, does nothing with it and returns a
14+
// response.
1315
async fn hello(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
1416
Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
1517
}
@@ -18,14 +20,29 @@ async fn hello(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>
1820
pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1921
pretty_env_logger::init();
2022

23+
// This address is localhost
2124
let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
2225

26+
// Bind to the port and listen for incoming TCP connections
2327
let listener = TcpListener::bind(addr).await?;
2428
println!("Listening on http://{}", addr);
2529
loop {
30+
// When an incoming TCP connection is received grab a TCP stream for
31+
// client<->server communication.
32+
//
33+
// Note, this is a .await point, this loop will loop forever but is not a busy loop. The
34+
// .await point allows the Tokio runtime to pull the task off of the thread until the task
35+
// has work to do. In this case, a connection arrives on the port we are listening on and
36+
// the task is woken up, at which point the task is then put back on a thread, and is
37+
// driven forward by the runtime, eventually yielding a TCP stream.
2638
let (stream, _) = listener.accept().await?;
2739

40+
// Spin up a new task in Tokio so we can continue to listen for new TCP connection on the
41+
// current task without waiting for the processing of the HTTP1 connection we just received
42+
// to finish
2843
tokio::task::spawn(async move {
44+
// Handle the connection from the client using HTTP1 and pass any
45+
// HTTP requests received on that connection to the `hello` function
2946
if let Err(err) = http1::Builder::new()
3047
.serve_connection(stream, service_fn(hello))
3148
.await

0 commit comments

Comments
 (0)