title: Recommended way to read from socket in HTTP server
body: <p>As a challenge I have implemented a basic web server in Java. When I open the raw <code>InputStream</code> I immediately go into a blocking read which reads the entire 400 or bytes of the HTTP request into a byte array. This works, however I then do not check for any more data and simply close the socket after sending a response.</p>
  
  <p>I'm wondering is there a more robust way to do this so as not to miss any data from the client. I thought of reading one byte at a time until <code>read</code> returned end of stream. However it instead sometimes blocks when there is no more data and confusingly the JavaDocs for <code>public abtract int InputStream.read()</code> says:</p>
  
  <p><code>If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.</code></p>
  
  <p>So it implies that two things can happen if the end of stream is reached: returning -1 and blocking. I am seeing blocking.</p>
  
  <p><em>My question is, with a protocol like HTTP, how should you read from the socket and how do you know when that's all the data you'll be getting in this connection?</em></p>