@@ -10,6 +10,8 @@ use hyper::service::service_fn;
10
10
use hyper:: { Request , Response } ;
11
11
use tokio:: net:: TcpListener ;
12
12
13
+ // An async function that consumes a request, does nothing with it and returns a
14
+ // response.
13
15
async fn hello ( _: Request < hyper:: body:: Incoming > ) -> Result < Response < Full < Bytes > > , Infallible > {
14
16
Ok ( Response :: new ( Full :: new ( Bytes :: from ( "Hello World!" ) ) ) )
15
17
}
@@ -18,14 +20,29 @@ async fn hello(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>
18
20
pub async fn main ( ) -> Result < ( ) , Box < dyn std:: error:: Error + Send + Sync > > {
19
21
pretty_env_logger:: init ( ) ;
20
22
23
+ // This address is localhost
21
24
let addr: SocketAddr = ( [ 127 , 0 , 0 , 1 ] , 3000 ) . into ( ) ;
22
25
26
+ // Bind to the port and listen for incoming TCP connections
23
27
let listener = TcpListener :: bind ( addr) . await ?;
24
28
println ! ( "Listening on http://{}" , addr) ;
25
29
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.
26
38
let ( stream, _) = listener. accept ( ) . await ?;
27
39
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
28
43
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
29
46
if let Err ( err) = http1:: Builder :: new ( )
30
47
. serve_connection ( stream, service_fn ( hello) )
31
48
. await
0 commit comments