title: "Connection reset by peer" when benchmarking a simple Rust HTTP server with ab
body: <p>I'm trying to write an extremely simple concurrent server in Rust to play with the language's concurrency primitives and its threading model.  Here's my code:</p>
  
  <pre><code>use std::io::prelude::*;
  use std::io::Result;
  use std::net::{TcpListener, TcpStream, Shutdown};
  use std::sync::{Arc, Mutex};
  use std::thread;
  
  fn handle_client(mut stream: TcpStream) -&gt; Result&lt;()&gt; {
      try!(stream.write(b"HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nPong!\r\n"));
      // try!(stream.shutdown(Shutdown::Both));
  
      Ok(())
  }
  
  fn main() {
      let listener = TcpListener::bind("127.0.0.1:1337").unwrap();
      // let count = Arc::new(Mutex::new(0));
  
      for stream in listener.incoming() {
          match stream {
              Ok(stream) =&gt; {
                  // let count = count.clone();
                  thread::spawn(move || {
                      let _ = handle_client(stream);
  
                      // let mut count = count.lock().unwrap();
                      // *count += 1;
                      // println!("{:?}", *count);
                  });
              }
              Err(e) =&gt; {
                  println!("Error: {}", e);
              }
          }
      }
  
      drop(listener);
  }
  </code></pre>
  
  <p>When I run <code>ab -c 100 -n 100 http://127.0.0.1:1337/</code> with the program running as listed above, I get <code>apr_socket_recv: Connection reset by peer (104)</code> almost immediately.  Why?</p>
  
  <p>When I add <code>try!(stream.shutdown(Shutdown::Both));</code> (commented out near the top, above) I no longer get the <code>apr_socket_recv</code> error like before, but apachebench gives me results that say 199 failed requests due to exceptions.  Why?  What am I doing wrong?</p>
  
  <pre><code>Concurrency Level:      100
  Time taken for tests:   0.008 seconds
  Complete requests:      100
  Failed requests:        199
     (Connect: 0, Receive: 0, Length: 0, Exceptions: 199)
  Total transferred:      500 bytes
  </code></pre>