]> piware.de Git - learn-rust.git/blobdiff - async-http/src/main.rs
async-http: Serve requests in parallel in threads
[learn-rust.git] / async-http / src / main.rs
index 09ca609eaa0d6333fc08cd86cfb08b3ca936dae2..c2884082c095f96dcb4598483b484ca66e4d92fd 100644 (file)
@@ -1,39 +1,47 @@
 use std::fs;
-use std::io::prelude::*;
-use std::net::TcpListener;
-use std::net::TcpStream;
+use std::time::Duration;
 
-fn main() {
-    // Listen for incoming TCP connections on localhost port 7878
-    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
+use async_std::prelude::*;
+use async_std::net::{ TcpListener, TcpStream };
+use async_std::task;
+use futures::stream::StreamExt;
+
+#[async_std::main]
+async fn main() {
+    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
 
-    // Block forever, handling each request that arrives at this IP address
-    for stream in listener.incoming() {
-        let stream = stream.unwrap();
+    // Listen for incoming TCP connections on localhost port 7878
+    let listener = TcpListener::bind("127.0.0.1:7878").await.unwrap();
 
-        handle_connection(stream);
-    }
+    listener.incoming().for_each_concurrent(/* limit */ None, |tcpstream| async move {
+        let tcpstream = tcpstream.unwrap();
+        task::spawn(handle_connection(tcpstream));
+    }).await;
 }
 
-fn handle_connection(mut stream: TcpStream) {
+async fn handle_connection(mut stream: TcpStream) {
     // Read the first 1024 bytes of data from the stream
     let mut buffer = [0; 1024];
-    stream.read(&mut buffer).unwrap();
-
-    let get = b"GET / HTTP/1.1\r\n";
+    assert!(stream.read(&mut buffer).await.unwrap() > 0);
 
     // Respond with greetings or a 404,
     // depending on the data in the request
-    let (status_line, filename) = if buffer.starts_with(get) {
-        ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
+    let (status_line, filename) = if buffer.starts_with(b"GET / HTTP/1.1\r\n") {
+        ("HTTP/1.1 200 OK", "index.html")
+    } else if buffer.starts_with(b"GET /sleep HTTP/1.1\r\n") {
+        task::sleep(Duration::from_secs(5)).await;
+        // sync version, to demonstrate concurrent async vs. parallel threads
+        // std::thread::sleep(Duration::from_secs(5));
+        ("HTTP/1.1 201 Sleep", "index.html")
     } else {
-        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
+        ("HTTP/1.1 404 NOT FOUND", "404.html")
     };
     let contents = fs::read_to_string(filename).unwrap();
+    log::info!("GET {} {}", filename, status_line);
 
     // Write response back to the stream,
     // and flush the stream to ensure the response is sent back to the client
-    let response = format!("{status_line}{contents}");
-    stream.write_all(response.as_bytes()).unwrap();
-    stream.flush().unwrap();
+    let response = format!("{status_line}\r\n\r\n{contents}");
+    stream.write_all(response.as_bytes()).await.unwrap();
+    stream.flush().await.unwrap();
 }