title: Socket reading using BufferedInputStream
body: <p>I'm using Java's <code>BufferedInputStream</code> class to read bytes sent to a socket.
  The data to the socket is HTTP form so generally is a header with defined content-length, then some content.</p>
  
  <p>The problem I'm having is that sometimes <code>BufferedInputStream.read()</code> will not read the full amount of data sent to it. It returns the number of bytes read but this is much less than has been sent. I have verified the bytes sent with Wireshark and can confirm the full message is being transmitted.)</p>
  
  <p>Sample code below:</p>
  
  <pre><code>BufferedInputStream inFromClient = new BufferedInputStream(socket.getInputStream());
  int contentLength = getContentLengthFromHeader();    
  byte[] b = new byte[contentLength];
  int bytesRead = inFromClient.read(b, 0, contentLength);
  </code></pre>
  
  <p>Once read() is finished sometimes <code>bytesRead</code> is equal to <code>contentLength</code> but on other occasions read() does not seem to read as far as the end of the content.
  Does anyone have any ideas on what is happening? Is Java buffering output? Are there better ways of reading from sockets?</p>