title: Socket input stream hangs on final read. Best way to handle this?
body: <p>I'm a bit stumped on how to avoid my socket hanging on read.  Here's my code:</p>
  
  <pre><code>    Socket socket = new Socket("someMachine", 16003);
      OutputStream outputStream = socket.getOutputStream();
      InputStream inputStream = socket.getInputStream();
      try {
          outputStream.write(messageBuffer.toByteArray());
          outputStream.flush();
          BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
          StringBuffer response = new StringBuffer();
          int result;
          while ((result = in.read()) != -1) {
              response.append(Character.toChars(result));
              System.out.println(result);
          }
          System.out.println("Done!");  //never gets printed
       } catch (...) {}
  </code></pre>
  
  <p>The above code successfully reads all the data from the stream but then hangs.  Reading up on the net I was expecting to receive a -1 from the server (which I can't control) to indicate that I had reached the end of stream but instead I get this:</p>
  
  <pre><code>(Lots of data above this point)
  57
  10
  37
  37
  69
  79
  70
  10
  </code></pre>
  
  <p>It then hangs.  So, my questions are:</p>
  
  <p>1) Have I coded this wrong or is there an issue with the server's response?</p>
  
  <p>2) If there is an issue with the server's response (i.e. no -1 being returned), how can I work around this (i.e. to stop reading when it hangs).</p>
  
  <p>Any help appreciated!</p>