The Big Build: A Web Server
This is it β the grand finale! π Today we build something real: a tiny web server. A web server is a program that waits patiently for visitors, and when someone shows up, it hands them a web page. Itβs like a friendly shopkeeper who greets everyone who walks through the door. πͺ
How does a web server work?
When you type a website address into a browser, your browser sends a little message called a request β basically, βHey, can I see your page, please?β The server reads that request and sends back a response β the actual page!
The plan
Our server needs to do three things, over and over:
- Listen at an address (like the standβs street corner).
- Read each visitorβs request.
- Write back a response that says βHello!β
In Rust, we use a tool called TcpListener to listen for visitors. Here is a sketch
of the idea. Read it like a story β you donβt need every detail!
use std::io::Write;
use std::net::TcpListener;
fn main() {
// 1. Listen at this address on our computer
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
println!("Listening on 127.0.0.1:7878");
// 2. Wait for visitors, one at a time
for stream in listener.incoming() {
let mut stream = stream.unwrap();
println!("Got a connection! Sending the hello page.");
// 3. Write back a simple web page that says Hello!
let response = "HTTP/1.1 200 OK\r\n\r\nHello!";
stream.write_all(response.as_bytes()).unwrap();
}
}
When you start this server, your terminal would print a log like this. Each time a
browser visits http://127.0.0.1:7878, a new line pops up!
That funny-looking 127.0.0.1 means βthis very computer,β and 7878 is like a
door number where our server waits. πͺ
Sending the hello page. to your
own greeting, then press βΆ Run. Imagine real visitors seeing your words!
Quick quiz
What does a web server do when a visitor sends a request?
Yes! A server listens for requests and sends back responses β just like a lemonade stand serving thirsty visitors!
TcpListener to listen
at an address, read each request, and write
back a response. π And here's the remarkable part: you went all the way from
your very first Hello World to a real web server. That's a serious journey.
Take a moment to be proud β then keep building! π¦π