Commit 76817597 authored by Chris's avatar Chris
Browse files

[multi-threaded-web-server] some performance improvements

parent feae0029
Loading
Loading
Loading
Loading
+2 −2
Original line number Diff line number Diff line
@@ -9,7 +9,7 @@ use std::{

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
    sender: Option<mpsc::SyncSender<Job>>,
}

type Job = Box<dyn FnOnce() + Send + 'static,>;
@@ -18,7 +18,7 @@ impl ThreadPool {
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();
        let (sender, receiver) = mpsc::sync_channel(10000);
        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);
+27 −11
Original line number Diff line number Diff line
@@ -5,12 +5,25 @@ use std::{
    thread,
    time::Duration,
};
use std::collections::HashMap;
use std::process::exit;
use std::sync::Arc;
use multi_threaded_web_server::ThreadPool;

fn main() {
    let mut html = HashMap::new();
    html.insert("hello.html", fs::read_to_string("hello.html").unwrap_or_else(|error| {
        eprintln!("error when reading {}: {}", "hello.html", error);
        exit(1);
    }));
    html.insert("404.html", fs::read_to_string("404.html").unwrap_or_else(|error| {
        eprintln!("error when reading {}: {}", "404.html", error);
        exit(1);
    }));
    let html = Arc::new(html);

    println!("[multi-threaded-web-service] application started");
    let pool = ThreadPool::new(4);
    let pool = ThreadPool::new(1);

    let listener = TcpListener::bind("127.0.0.1:7878").unwrap_or_else(|error| {
        eprintln!("error when binding to port 7878: {}", error);
@@ -26,15 +39,16 @@ fn main() {

        println!("[multi-threaded-web-service] connection established");

        pool.execute(|| {
            handle_connection(stream);
        let html_arc = Arc::clone(&html);
        pool.execute(move || {
            handle_connection(stream, &html_arc);
        })
    }

    println!("shutting down...");
}

fn handle_connection(mut stream: TcpStream) {
fn handle_connection(mut stream: TcpStream, html_strings: &HashMap<&'static str, String>) {
    let buf_reader = BufReader::new(&stream);

    // note: the book suggests only reading the request line, but I want to be able to log the whole request
@@ -43,7 +57,7 @@ fn handle_connection(mut stream: TcpStream) {
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();
    println!("Received request: {http_request:#?}");
    // println!("Received request: {http_request:#?}");
    let request_verb_type_version = String::from("");
    let request_verb_type_version = http_request.get(0).unwrap_or(&request_verb_type_version);

@@ -58,17 +72,19 @@ fn handle_connection(mut stream: TcpStream) {



    let response_body = fs::read_to_string(html_file_name).unwrap_or_else(|error| {
        eprintln!("error when reading {}: {}", html_file_name, error);
        exit(1);
    });
    // let response_body = fs::read_to_string(html_file_name).unwrap_or_else(|error| {
    //     eprintln!("error when reading {}: {}", html_file_name, error);
    //     exit(1);
    // });
    let response_body = html_strings.get(html_file_name).unwrap();
    let response_body_length = response_body.len();

    let response =
        format!("{}\r\nContent-Length:{}\r\n\r\n{}",
        format!("{}{}\r\nContent-Length:{}\r\n\r\n{}",
                status_line,
                "\r\nConnection: close",
                response_body_length,
                response_body);
    println!("response is {response}");
    // println!("response is {response}");
    stream.write_all(response.as_bytes()).unwrap();
}