Understanding TcpStream, what's the next step after accepting connection?

Hi everyone, I'm working through Chapter 21 of the Rust book (multithreaded web server).

I have a TcpListener that successfully accepts connections:

for stream in listener.incoming() {
    let stream = stream.unwrap();
    println!("Connection established!");
}

The terminal prints "Connection established!" when I visit the URL, but the browser just hangs.

Questions:

  1. Do I need to read from the stream first?
  2. Or should I write a response immediately?
  3. What's the minimum HTTP response format I need to send back?

I know I need to eventually parse HTTP requests, but right now I just want to understand the basic flow of:

  • Accept connection → ??? → Send something → Close connection

You don't have to read from the connection before sending a response.

use std::{
    io::{BufReader, prelude::*},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let response = "HTTP/1.1 200 OK\r\n\r\nbody";

    stream.write_all(response.as_bytes()).unwrap();
}

will work fine in your browser.[1]


  1. Even though we omitted the content-type header field. ↩︎