summaryrefslogtreecommitdiffstats
path: root/src/doc/book/listings/ch20-web-server/no-listing-07-final-code
diff options
context:
space:
mode:
Diffstat (limited to 'src/doc/book/listings/ch20-web-server/no-listing-07-final-code')
-rw-r--r--src/doc/book/listings/ch20-web-server/no-listing-07-final-code/404.html11
-rw-r--r--src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.lock6
-rw-r--r--src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.toml6
-rw-r--r--src/doc/book/listings/ch20-web-server/no-listing-07-final-code/hello.html11
-rw-r--r--src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/lib.rs92
-rw-r--r--src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/main.rs51
6 files changed, 177 insertions, 0 deletions
diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/404.html b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/404.html
new file mode 100644
index 000000000..88d8e9152
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/404.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>Hello!</title>
+ </head>
+ <body>
+ <h1>Oops!</h1>
+ <p>Sorry, I don't know what you're asking for.</p>
+ </body>
+</html>
diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.lock
new file mode 100644
index 000000000..f2d069f46
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.lock
@@ -0,0 +1,6 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "hello"
+version = "0.1.0"
+
diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.toml
new file mode 100644
index 000000000..fe619478a
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "hello"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/hello.html
new file mode 100644
index 000000000..fe442d6b9
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/hello.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>Hello!</title>
+ </head>
+ <body>
+ <h1>Hello!</h1>
+ <p>Hi from Rust</p>
+ </body>
+</html>
diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/lib.rs
new file mode 100644
index 000000000..54c0489ab
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/lib.rs
@@ -0,0 +1,92 @@
+use std::{
+ sync::{mpsc, Arc, Mutex},
+ thread,
+};
+
+pub struct ThreadPool {
+ workers: Vec<Worker>,
+ sender: Option<mpsc::Sender<Job>>,
+}
+
+type Job = Box<dyn FnOnce() + Send + 'static>;
+
+impl ThreadPool {
+ /// Create a new ThreadPool.
+ ///
+ /// The size is the number of threads in the pool.
+ ///
+ /// # Panics
+ ///
+ /// The `new` function will panic if the size is zero.
+ pub fn new(size: usize) -> ThreadPool {
+ assert!(size > 0);
+
+ 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)));
+ }
+
+ ThreadPool {
+ workers,
+ sender: Some(sender),
+ }
+ }
+
+ pub fn execute<F>(&self, f: F)
+ where
+ F: FnOnce() + Send + 'static,
+ {
+ let job = Box::new(f);
+
+ self.sender.as_ref().unwrap().send(job).unwrap();
+ }
+}
+
+impl Drop for ThreadPool {
+ fn drop(&mut self) {
+ drop(self.sender.take());
+
+ 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<thread::JoinHandle<()>>,
+}
+
+impl Worker {
+ fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
+ let thread = thread::spawn(move || loop {
+ let message = receiver.lock().unwrap().recv();
+
+ match message {
+ Ok(job) => {
+ println!("Worker {id} got a job; executing.");
+
+ job();
+ }
+ Err(_) => {
+ println!("Worker {id} disconnected; shutting down.");
+ break;
+ }
+ }
+ });
+
+ Worker {
+ id,
+ thread: Some(thread),
+ }
+ }
+}
diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/main.rs
new file mode 100644
index 000000000..3161c2ee5
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/no-listing-07-final-code/src/main.rs
@@ -0,0 +1,51 @@
+use hello::ThreadPool;
+use std::fs;
+use std::io::prelude::*;
+use std::net::TcpListener;
+use std::net::TcpStream;
+use std::thread;
+use std::time::Duration;
+
+fn main() {
+ let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
+ let pool = ThreadPool::new(4);
+
+ 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; 1024];
+ 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", "hello.html")
+ } else if buffer.starts_with(sleep) {
+ thread::sleep(Duration::from_secs(5));
+ ("HTTP/1.1 200 OK", "hello.html")
+ } else {
+ ("HTTP/1.1 404 NOT FOUND", "404.html")
+ };
+
+ let contents = fs::read_to_string(filename).unwrap();
+
+ let response = format!(
+ "{}\r\nContent-Length: {}\r\n\r\n{}",
+ status_line,
+ contents.len(),
+ contents
+ );
+
+ stream.write_all(response.as_bytes()).unwrap();
+ stream.flush().unwrap();
+}