Browse Source

Add ThreadPool

master
Noelle 4 years ago
parent
commit
73acd2bd44
2 changed files with 26 additions and 17 deletions
  1. 5
    0
      src/lib.rs
  2. 21
    17
      src/main.rs

+ 5
- 0
src/lib.rs View File

@@ -0,0 +1,5 @@
pub struct ThreadPool;

impl ThreadPool {
}

+ 21
- 17
src/main.rs View File

@@ -1,39 +1,43 @@
use std::net::{TcpStream, TcpListener};
use std::io::prelude::*;
use std::fs;
use std::thread;
use std::time::Duration;

use hello::ThreadPool;

fn main() {
let listener = TcpListener::bind("127.0.0.1:26382").unwrap();
let pool = ThreadPool::new(4);

for stream in listener.incoming() {
let stream = stream.unwrap();

handle_connecton(stream);
pool.execute(|| {
handle_connection(stream);
});
}
}

fn handle_connecton(mut stream: TcpStream) {
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";

if buffer.starts_with(get) {
// It's the request we want
let status_line = "HTTP/1.1 200 OK\r\n\r\n";
let contents = fs::read_to_string("hello.html").unwrap();
let response = format!("{}{}", status_line, contents);

stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
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 {
let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n";
let contents = fs::read_to_string("404.html").unwrap();
let response = format!("{}{}", status_line, contents);
("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();
}
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();




Loading…
Cancel
Save