Skip to content

Commit

Permalink
docs(example): add comments to the examples/hello.rs example (hyperiu…
Browse files Browse the repository at this point in the history
  • Loading branch information
technetos authored and 0xE282B0 committed Jan 12, 2024
1 parent 3a9bf81 commit b67e037
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions examples/hello.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
}
Expand All @@ -18,14 +20,29 @@ async fn hello(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>
pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
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
Expand Down

0 comments on commit b67e037

Please sign in to comment.