From 5718a0b54869b341bc74416bf82b716aa15d582c Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Tue, 26 Mar 2019 15:05:10 -0400 Subject: Finished web server project. Book done! --- hello_server/src/bin/main.rs | 44 ++++++++++++++++++++++ hello_server/src/lib.rs | 88 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 hello_server/src/bin/main.rs create mode 100644 hello_server/src/lib.rs (limited to 'hello_server/src') diff --git a/hello_server/src/bin/main.rs b/hello_server/src/bin/main.rs new file mode 100644 index 0000000..522777a --- /dev/null +++ b/hello_server/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello_server::ThreadPool; +use std::thread; +use std::time::Duration; +use std::io::prelude::*; +use std::fs; +use std::net::TcpStream; +use std::net::TcpListener; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4).unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + 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") + }; + + let contents = fs::read_to_string(filename).unwrap(); + let response = format!("{}{}", status_line, contents); + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/hello_server/src/lib.rs b/hello_server/src/lib.rs new file mode 100644 index 0000000..c8e6a3e --- /dev/null +++ b/hello_server/src/lib.rs @@ -0,0 +1,88 @@ +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::mpsc; +use std::thread; + +trait FnBox { + fn call_box(self: Box); +} + +impl FnBox for F { + fn call_box(self: Box) { + (*self)() + } +} + +type Job = Box; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +impl ThreadPool { + pub fn new(size: usize) -> Result { + if size <= 0 { + return Err("failed to create pool"); + } + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))?); + } + + Ok(ThreadPool { + workers, + sender, + }) + } + + pub fn spawn(f: F) -> thread::JoinHandle + where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static + { + thread::spawn(f) + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static + { + let job = Box::new(f); + self.sender.send(job).unwrap(); + } + +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + pub fn new(id: usize, receiver: Arc>>) + -> Result + { + let thread = thread::spawn(move || { + loop { + let job = receiver + .lock().expect("lock poisoned!") + .recv().unwrap(); + println!("worker {} got job; executing...", id); + + job.call_box(); + } + }); + + Ok(Worker { + id, + thread, + }) + } +} -- cgit v1.2.3