Accepting Connections

TcpListener, reading a request line, writing a response by hand.

Part 1 of 3Updated
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:7878")?;
    println!("listening on http://127.0.0.1:7878");

    for stream in listener.incoming() {
        let mut stream = stream?;
        let mut reader = BufReader::new(&stream);
        let mut request_line = String::new();
        reader.read_line(&mut request_line)?;

        let body = "hello";
        write!(
            stream,
            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
            body.len(),
            body
        )?;
    }
    Ok(())
}

That’s a working HTTP server. HTTP/1.1 is a text protocol β€” a request line, headers, a blank line, then an optional body. Content-Length is what tells the client where the body ends.

This server handles exactly one connection at a time. Fix that in part 2.