title: HTTP Request Handler Connection Reset Error
body: <p>I am writing up a simple HTTP request handler, but kept randomly encountering <strong>Connection Reset</strong> errors while transmitting files over to the client browser.</p>
  
  <p>Since my program is rather large, I will simplify the codes a bit below:</p>
  
  <pre><code>public class HTTPRequestHandler implements Runnable {
      private Queue&lt;HTTPRequest&gt; requests;
      private volatile boolean flag;
      ...
      public void run() {
          flag = true;
          while (flag) {
              HTTPRequest request = null;
              synchronized(this) {
                  if (requests.size &gt; 0) {
                       request = requests.removeFirst();
                  }
              }
  
              if (request != null) {
                  handleRequest(request);
              }
          }
      }
      ...
      private void handleRequest(HTTPRequest request) {
          ...
          try {
              // Send HTTP Header
              request.getSocket().getOutputStream().write(message.getHeader().getBytes());
  
              // Send HTTP Message Body
              Object messageBody = message.getMessageBody();
              if (messageBody != null &amp;&amp; messageBody.getClass() == File.class) {
                  Files.copy(((File)messageBody).toPath(), request.getSocket().getOutputStream());
                  request.getSocket().getOutputStream().flush();
              } else if (messageBody != null) {
                  ...
              }
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          ...
      }
  </code></pre>
  
  <p>I was able to get this part to work most of the times (not always) on various browsers on a local machine, but it never works at all on a remote machine. It is happening randomly for mainly large file and sometimes for small files as well.</p>
  
  <p>As for HTTP header, I currently have the program close the connection after each complete response.</p>