Android: How Reliable is InputStream.read() and its "-1" return?
<p>My question is related to a method <strong>InputStream.read()</strong> - socket programming.</p>

<p>Every source i have found states that when the server or client closes the connection, "-1" is returned.</p>

<p>But, "what if", just saying, "what if" the connection <em>is</em> closed but <strong>read()</strong> does not return "-1"? We rely on someone else's code. The reason i am worried is because in order to read the remote end's input, one will have to create an infinite loop and I have always been thought to stay away from infinite loops. With Java however, it looks like I do not have a choice! Here is a sample:</p>

<pre><code>int b = 0;
    while (true)
    {
      b = inputStream.read()
      if (b == -1) break; // connection closed
    }
</code></pre>

<p>or </p>

<pre><code> while (b &gt; -1)
 b = inputStream.read()
</code></pre>

<p>What <em>if</em> something happens, and -1 never becomes true? One will end up in an infinite loop increasing the temperature of someone's device and wasting CPU cycles! How can one be certain? </p>

<p>References: [http://developer.android.com/reference/java/io/InputStream.html#read%28%29][1] and [http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read%28byte[],%20int,%20int%29][2] </p>

<p>I want to have a fail-safe check. What I have done in the loop is also do a check whether socket has become null and if so, break the loop.</p>

<pre><code> while (b &gt; -1)
    {
      b = inputStream.read()

      if (socket == null) break;
      if (outputStream == null) break;
    }
</code></pre>

<p>What else can I do to ensure the loop exists in case "-1" never becomes true?</p>
