title: What does 'end of stream' mean when working with sockets
body: <p>When working with Sockets in Java, how can you tell whether the client has finished sending all (binary) data, before you could start processing them. Consider for example:</p>
  
  <pre><code>istream = new BufferedInputStream (socket.getInputStream());
  ostream = new BufferedOutputStream(socket.getOutputStream());
  
  byte[] buffer = new byte[BUFFER_SIZE];
  
  int count;
  while(istream.available() &gt; 0 &amp;&amp; (count = istream.read(buffer)) != -1)
  {
      // do something..
  }
  
  // assuming all input has been read
  ostream.write(getResponse());       
  ostream.flush();
  </code></pre>
  
  <p>I've read similar posts on SO such as <a href="https://stackoverflow.com/questions/534964/why-is-the-end-of-the-input-stream-never-reached-using-java-sockets">this</a>, but couldn't find a conclusive answer. While my solution above works, my understanding is that you can never really tell if the client has finished sending all data. If for instance the client socket sends a few chunks of data and then blocks waiting for data from another data source before it could send more data, the code above may very well assume that the client has finished sending all data since istream.available() will return 0 for the <em>current</em> stream of bytes.</p>