title: Is there a way to check if a connection has been closed then finish the thread?
body: <p>With a code similar to that of <a href="https://rosettacode.org/wiki/Echo_server#Rust" rel="nofollow noreferrer">this example</a>, a connection goes on forever because the infinite loop never stops. I modified it a bit in order to allow reading not to be blocking the thread:</p>
  
  <pre><code>use std::net::{TcpListener, TcpStream};
  use std::io::{BufRead, BufReader};
  use std::thread;
  
  fn main() {
      let listener = TcpListener::bind("127.0.0.1:4444").unwrap();
      println!("Server is running on 127.0.0.1:4444 ...");
  
      for stream in listener.incoming() {
          let stream = stream.unwrap();
          stream
              .set_nonblocking(true)
              .expect("Failed to set stream as nonblocking");
          thread::spawn(move || handle_client(stream));
      }
  }
  
  fn handle_client(stream: TcpStream) {
      let mut stream = BufReader::new(stream);
      println!("New client logged");
  
      loop {
          let mut recv_buffer = String::new();
          println!("Before reading");
          let recv_data_size = stream
              .read_line(&amp;mut recv_buffer)
              .expect("Error when reading line");
  
          if recv_data_size &gt; 0 {
              println!("{}", recv_buffer);
          }
      }
  }
  </code></pre>
  
  <p>The client is really simple, connects then send <code>Hello!</code> to the server:</p>
  
  <pre><code>use std::io::prelude::*;
  use std::net::TcpStream;
  
  fn main() {
      let mut stream = TcpStream::connect("127.0.0.1:4444").unwrap();
      let _ = stream.write("Hello!".as_bytes());
  }
  </code></pre>
  
  <p>When client sends its string and <em>disconnects</em>, the server goes into an infinite loop and prints <code>Before reading</code> indefinitely. It never knows when to close connection, even though the client ended it long ago.</p>
  
  <p>Is there a way in Rust to check if distant connection has been closed (if possible without having to set a timeout), then finish properly the thread on which it is running?</p>