Introduction
Building a web server from scratch is an excellent way to explore Rust's concurrency features, and its focus on performance and safety makes it a great choice for systems programming. We will build a simple Rust multithreaded web server without using third-party web frameworks. Apart from handling basic HTTP requests and serving static files, we will see the usage of a thread pool for concurrency.
Setting Up the Project
Firstly, let's set up a new Rust project and configure the necessary dependencies. Open your terminal and run the following commands.
cargo new rust_web_server
cd rust_web_server
Writing the Web Server Code
The `main.rs` File
Replace the contents of 'src/main.rs' with the following code
use std::net::TcpListener;
use std::net::TcpStream;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Write;
use std::fs;
use std::thread;
use std::time::Duration;
use rust_web_server::ThreadPool;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
}
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&mut stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let response = format!(
"{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
);
stream.write_all(response.as_bytes()).unwrap();
}
In this code, we have set up a basic web server using the 'std::net' module, handle incoming connections, and use a thread pool 'ThreadPool' to concurrently handle multiple requests.
The 'lib.rs' File
Create a new file called 'lib.rs' in the 'src' directory and add the following code.
use std::thread;
use std::sync::mpsc;
use std::sync::Mutex;
use std::sync::Arc;
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
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 }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || {
while let Ok(job) = receiver.lock().unwrap().recv() {
println!("Worker {} got a job; executing.", id);
job();
}
});
Worker { id, thread }
}
}
In this code, we define a simple thread pool 'ThreadPool' that uses the 'std::sync::mpsc' channel to communicate with worker threads 'Worker'. Each worker thread runs in a loop, waiting for jobs and executing them.
Creating Static HTML Files
Now, create two static HTML files, 'hello.html' and '404.html', in the 'src' directory.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>Hi from a Rustian.</p>
</body>
</html>



Join the conversation! Your thoughts help the community grow.