|
@@ -3,16 +3,32 @@ use std::io::prelude::*;
|
|
|
use std::net::TcpListener;
|
|
|
use std::net::TcpStream;
|
|
|
use std::fs::File;
|
|
|
+use std::thread;
|
|
|
+use std::time::Duration;
|
|
|
+
|
|
|
+extern crate helloweb;
|
|
|
+use helloweb::ThreadPool;
|
|
|
+
|
|
|
+
|
|
|
+// struct ThreadPool;
|
|
|
+// impl ThreadPool {
|
|
|
+// fn new(size: u32) -> ThreadPool { ThreadPool }
|
|
|
+// fn execute<F>(&self, f: F)
|
|
|
+// where F: FnOnce() + Send + 'static {}
|
|
|
+// }
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
|
|
+ let pool = ThreadPool::new(4);
|
|
|
|
|
|
for stream in listener.incoming() {
|
|
|
// "unwrap" means "just crash if there's an error"
|
|
|
let stream = stream.unwrap();
|
|
|
|
|
|
- handle_connection(stream);
|
|
|
+ pool.execute(|| {
|
|
|
+ handle_connection(stream);
|
|
|
+ });
|
|
|
}
|
|
|
}
|
|
|
|
|
@@ -25,10 +41,14 @@ fn handle_connection(mut stream: TcpStream) {
|
|
|
|
|
|
stream.read(&mut buffer).unwrap();
|
|
|
|
|
|
- let get = b"GET / HTTP/1.1\r\n";
|
|
|
+ let get = b"GET / HTTP/1.1\r\n";
|
|
|
+ let sleep = b"GET /sleep HTTP/1.1\r\n";
|
|
|
|
|
|
let (status_line, filename) = if buffer.starts_with(get) {
|
|
|
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
|
|
|
+ } else if buffer.starts_with(sleep) {
|
|
|
+ thread::sleep(Duration::from_secs(5));
|
|
|
+ ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
|
|
|
} else {
|
|
|
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
|
|
|
};
|