diff --git a/examples/hello.rs b/examples/hello.rs index 167c9a0176..a11199adb8 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -10,6 +10,8 @@ use hyper::service::service_fn; use hyper::{Request, Response}; use tokio::net::TcpListener; +// An async function that consumes a request, does nothing with it and returns a +// response. async fn hello(_: Request) -> Result>, Infallible> { Ok(Response::new(Full::new(Bytes::from("Hello World!")))) } @@ -18,14 +20,29 @@ async fn hello(_: Request) -> Result pub async fn main() -> Result<(), Box> { pretty_env_logger::init(); + // This address is localhost let addr: SocketAddr = ([127, 0, 0, 1], 3000).into(); + // Bind to the port and listen for incoming TCP connections let listener = TcpListener::bind(addr).await?; println!("Listening on http://{}", addr); loop { + // When an incoming TCP connection is received grab a TCP stream for + // client<->server communication. + // + // Note, this is a .await point, this loop will loop forever but is not a busy loop. The + // .await point allows the Tokio runtime to pull the task off of the thread until the task + // has work to do. In this case, a connection arrives on the port we are listening on and + // the task is woken up, at which point the task is then put back on a thread, and is + // driven forward by the runtime, eventually yielding a TCP stream. let (stream, _) = listener.accept().await?; + // Spin up a new task in Tokio so we can continue to listen for new TCP connection on the + // current task without waiting for the processing of the HTTP1 connection we just received + // to finish tokio::task::spawn(async move { + // Handle the connection from the client using HTTP1 and pass any + // HTTP requests received on that connection to the `hello` function if let Err(err) = http1::Builder::new() .serve_connection(stream, service_fn(hello)) .await