I have a TCP server listening on requests in an infinite loop:
use std::io::prelude::*;
use std::net::TcpStream;
use std::net::TcpListener;
fn main() {
let listener = TcpListener::bind("0.0.0.0:7878").unwrap();
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let response = "HTTP/1.1 200 OK\r\n\r\nsdfuhgsjdfghsdfjk";
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
}
How can I break the loop after a period of time (timeout) ?
After the timeout elapsed, I need the listening loop to stop:
- right that moment if there is no incoming stream (i.e if there is no streams incoming and there might not be any more in the future, I need the server to stop waiting in vain)
- after processing one last stream if there is already one incoming at that moment