title: how to detect end of socket InputStream?
body: <p>The following code should detect that there are no more bytes to be read. However it simply hangs until client connection is closed.</p>
  
  <p><strong>Server</strong></p>
  
  <pre><code>        //...
  
          StringBuilder builder = new StringBuilder(128);
          byte[] buffer = new byte[1024];
          int length = 0;
  
          while ((length = socket.getInputStream().read(buffer)) != -1) {
              System.out.println(length);
              builder.append(new String(buffer));
              System.out.println(builder.toString());
          }
  </code></pre>
  
  <p><strong>Client</strong></p>
  
  <pre><code>   //...
  
      OutputStream stream = clientSocket.getOutputStream();
      stream.write("LIST".getBytes());
      stream.flush();
  </code></pre>
  
  <p>The API and the previous answer on such question states that -1 should mean that there are no characters to be read, however this loop writes:</p>
  
  <ul>
  <li><p>4</p></li>
  <li><p>LIST</p></li>
  <li><p>hangs for 20 seconds until client closes socket and picks up -1 to terminate loop.</p></li>
  </ul>
  
  <p>How could i properly detect that there are no more characters in the stream ?</p>
  
  <p>Connection should remain open after this.</p>
  
  <p>I could send number of bytes in advance or special character, but is it possible to detect that there is nothing to be read any longer even if connection is still active.</p>