Stream writting

Trying replicating this server writing example, but it is not returning the related HTML file
my code:

use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::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 mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    let contents = fs::read_to_string("hello.html").unwrap();
    println!("{}", contents); // OK
    let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
    stream.write(response.as_bytes()).unwrap(); // Not OK
    stream.flush().unwrap();
}

Structure and output

Last time I saw this issue, the web browser was still trying to send you the request while you were trying to send it the response, neither of you reading from the other part, causing a deadlock.

Make sure you keep reading until you get a double newline.

mmm, not getting you, the file is read and I was able to get it printed using the:

    let contents = fs::read_to_string("hello.html").unwrap();
    println!("{}", contents); // OK

I added double lines to end of the file (no

Well, your

stream.read(&mut buffer).unwrap();

might not read very many bytes if the full request was not immediately ready.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.