get a response ? I can get it working in terminal.
use std::fs;
use std::io::prelude::*;
use std::net::TcpStream;
use std::net::TcpListener;
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();
let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
What do you mean by "I can get it work in the terminal"?
When saying your browser does not get a response, is this really true or does it consider the response invalid HTTP?
Which browsers have you used to check? How do you run and compile the program? What is the contents of the html file?
edit
I just was able to check locally, at least chromium (and therefore I assume other WebKit browsers as well) displays my content as soon as I manually shutdown
the TcpStream
:
stream.shutdown(Shutdown::Both).unwrap();
Some more on this: Since you do not close the connection properly, and also do not specify a content type or a chunked transfer, the browser assumes that additional data might be transfered and will wait for it. It considers the improperly dropped connection as an error (but seems to not gracefully handle it). curl
though and maybe other command line tools will just show what they get, as they usually pipe the stream to stdout anyway once headers are read.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Request Recieved.</title>
</head>
<body>
<h1>Hello.</h1>
<p>Response from my Rust web server.</p>
</body>
</html>
This will not necessarily write all bytes, use write_all
instead.
Lets try that ...
Same for read
. read_to_end
would probably be better.
I have two reads. change them both ?
Where's the other one?
let contents = fs::read_to_string("hello.html").unwrap();
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.