A simple multithreaded web server implemented in Rust, from Chapter 20 of The Rust Programming Language book. This project demonstrates key concepts in systems programming, including thread management, message passing, and basic networking.
The server listens on 127.0.0.1:7878
and handles incoming HTTP requests. It supports basic routes and uses a custom thread pool to manage connections efficiently.
- Multithreaded Design: Uses a custom thread pool to handle multiple client requests concurrently.
- Basic Routing: Responds to
GET /
with an HTML file,GET /sleep
with a delayed response, and other routes with a 404 page. - Graceful Shutdown: Cleans up threads upon server shutdown.
-
Clone this repository:
git clone https://github.com/imaazkhalid/web_server.git cd web_server
-
Start the server:
cargo run
-
Open a browser and navigate to
http://127.0.0.1:7878
.
GET /
: Responds with the content ofhello.html
.GET /sleep
: Simulates a delayed response by waiting 5 seconds before returninghello.html
.- Other routes: Returns a 404 response with the content of
404.html
.
src/main.rs
:- Handles TCP connections, parses HTTP requests, and generates responses.
- Manages the server lifecycle and integrates the thread pool.
src/lib.rs
:- Implements a custom
ThreadPool
for managing worker threads and executing jobs concurrently.
- Implements a custom
The ThreadPool
is a simplified thread pool implementation that demonstrates:
- Job Queueing: Uses a channel (
mpsc::Sender
andReceiver
) to queue tasks. - Worker Threads: Each worker continuously listens for jobs and executes them.
- Graceful Shutdown: Ensures all threads are properly terminated during the server shutdown.
Initializes the thread pool with a specified number of threads.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
// ... setup workers and channels ...
}
Queues a new task for execution.
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();
}
Represents a thread that processes tasks from the queue.
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
This project provides hands-on experience with:
- TCP networking and handling HTTP requests
- Using Rust's concurrency primitives (
thread
,mpsc
,Mutex
, andArc
) - Implementing the Drop trait for resource cleanup
- Building and managing a thread pool
- Static Content Only: Currently serves hardcoded HTML files.
- Limited Routing: No dynamic route handling or request parsing beyond the basics.
- No Logging: Could benefit from structured logging for better debugging and monitoring.
- Scalability: Not optimized for high-concurrency scenarios.
This web server is an excellent learning exercise for understanding the foundations of Rust's concurrency and networking capabilities.