From 67cdcc2e12118becb823e20a40cc2687f2b8425a Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Wed, 27 Mar 2019 15:32:37 -0400 Subject: Started Rust in Action MEAP. --- rust-book/hello_server/404.html | 19 ++++++ rust-book/hello_server/Cargo.lock | 4 ++ rust-book/hello_server/Cargo.toml | 7 ++ rust-book/hello_server/hello.html | 18 +++++ rust-book/hello_server/src/bin/main.rs | 46 +++++++++++++ rust-book/hello_server/src/lib.rs | 117 +++++++++++++++++++++++++++++++++ 6 files changed, 211 insertions(+) create mode 100755 rust-book/hello_server/404.html create mode 100755 rust-book/hello_server/Cargo.lock create mode 100755 rust-book/hello_server/Cargo.toml create mode 100755 rust-book/hello_server/hello.html create mode 100755 rust-book/hello_server/src/bin/main.rs create mode 100755 rust-book/hello_server/src/lib.rs (limited to 'rust-book/hello_server') diff --git a/rust-book/hello_server/404.html b/rust-book/hello_server/404.html new file mode 100755 index 0000000..b106938 --- /dev/null +++ b/rust-book/hello_server/404.html @@ -0,0 +1,19 @@ + + + + + + + Hello! + + + +

+ Oops! +

+

+ Sorry, Idk what you're asking for. +

+ + + diff --git a/rust-book/hello_server/Cargo.lock b/rust-book/hello_server/Cargo.lock new file mode 100755 index 0000000..738010c --- /dev/null +++ b/rust-book/hello_server/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "hello_server" +version = "0.1.0" + diff --git a/rust-book/hello_server/Cargo.toml b/rust-book/hello_server/Cargo.toml new file mode 100755 index 0000000..39057cc --- /dev/null +++ b/rust-book/hello_server/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_server" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/hello_server/hello.html b/rust-book/hello_server/hello.html new file mode 100755 index 0000000..869c8f9 --- /dev/null +++ b/rust-book/hello_server/hello.html @@ -0,0 +1,18 @@ + + + + + + Hello! + + + +

+ Hello! +

+

+ Hi from Rust +

+ + + diff --git a/rust-book/hello_server/src/bin/main.rs b/rust-book/hello_server/src/bin/main.rs new file mode 100755 index 0000000..bcf1e46 --- /dev/null +++ b/rust-book/hello_server/src/bin/main.rs @@ -0,0 +1,46 @@ +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().take(2) { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + + println!("shutting down..."); + +} + +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/rust-book/hello_server/src/lib.rs b/rust-book/hello_server/src/lib.rs new file mode 100755 index 0000000..cd1f616 --- /dev/null +++ b/rust-book/hello_server/src/lib.rs @@ -0,0 +1,117 @@ +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::mpsc; +use std::thread; + +enum Message { + NewJob(Job), + Terminate, +} + +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(Message::NewJob(job)).unwrap(); + } + +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for _ in &mut self.workers { + self.sender.send(Message::Terminate).unwrap(); + } + + println!("shutting down all workers..."); + + for worker in &mut self.workers { + println!("shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + pub fn new(id: usize, receiver: Arc>>) + -> Result + { + let thread = thread::spawn(move || { + loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("worker {} got job, executing...", id); + job.call_box(); + }, + Message::Terminate => { + println!("worker {} was told to terminate...", id); + break; + }, + } + } + }); + + Ok(Worker { + id, + thread: Some(thread), + }) + } +} -- cgit v1.2.3