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:
- Do I need to read from the stream first?
- Or should I write a response immediately?
- 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
jofas
2
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.
system
Closed
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.