I'm very new to Rust and trying to write a simple chat app without using any external crates just as a start. I already have a very simple backend server (based on the rust book example) which binds to localhost port 8080 and respond to GET or POST request. Now I'm trying to do the client side where I use TcpStream::connect
to connect to the server, and repeatedly send POST requests every 5 seconds, just as a test. What I'm witnessing is that if TcpStream::connect
is outside the loop then after the first message the connection is lost Broken pipe (os error 32)
whereas within the loop it works but to me it does not make sense to do connect request every iteration. I am probably missing something very obvious, and appreciate all the help.
Client code snippet
use std::io::{self, Write, BufRead, Read};
use std::net::{TcpStream, Shutdown};
use std::thread;
use std::time::Duration;
fn main() -> io::Result<()> {
let mut stream = TcpStream::connect( "127.0.0.1:8080")?;
loop {
let body = String::from("testing");
let request = format!(
"POST /path/to/endpoint HTTP/1.1\r\n\
Host: example.com\r\n\
Content-Type: application/json\r\n\
Content-Length: {}\r\n\
\r\n\
{}",
body.len(),
body
);
stream.write_all(request.as_bytes())?;
println!("Sent: {}", request);
thread::sleep(Duration::from_secs(5));
}
}