Augusto Dwenger J.
92b4db36a6
This commit includes the version of the ThreadPool from the official rust book [1] with a small improvment regarding the pool creation. This version does not panic if it fails to create the pool it will return a Result with a possible ThreadPoolCreatError. Everything else is equal to the tutorial implementation. [1] https://doc.rust-lang.org/book/ch20-00-final-project-a-web-server.html
39 lines
865 B
Rust
39 lines
865 B
Rust
use poolth::ThreadPool;
|
|
use std::io::{Read, Write};
|
|
use std::net::TcpListener;
|
|
use std::net::TcpStream;
|
|
|
|
fn main() {
|
|
println!("Hello World :D");
|
|
|
|
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; 1024];
|
|
|
|
stream.read(&mut buffer).unwrap();
|
|
|
|
// println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
|
|
|
|
let contents = "Hello World";
|
|
|
|
let response = format!(
|
|
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
|
|
contents.len(),
|
|
contents
|
|
);
|
|
|
|
stream.write(response.as_bytes()).unwrap();
|
|
stream.flush().unwrap();
|
|
}
|