title: Android socket inputstream read (followed by an EPIPE)
body: <p>I am creating some client-side socket software to read events from a server. (For example, streaming stock quotes).</p>
  
  <p><strong>PROBLEM:</strong> .read(b); is returning <strong>immediately</strong> with a value of <strong>-1</strong>. This causes an infinte loop and the phone becomes very hot. Additionally, all checks to s.isConnected(), isOpen(), isBound() return true. Essentially the socket <em>looks connected</em>. (This is an error scenario, so any value of .setSoTimeout(x) has no effect. 12 minutes, or leave empty. The .read(b) always returns -1 immediately).</p>
  
  <p>When I write to it later, via the getOutputStream(), I receive an exception EPIPE (broken pipe).</p>
  
  <p>Here's the core code (log statements/value checks omitted for brevity).</p>
  
  <pre><code>s.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MILLIS);
  
  byte[] b = new byte[1024];
  while (s.isConnected()) {
      int bytesToRead = s.getInputStream().read(b);
      if (bytesToRead &lt;= 0) {
          LOGGER.debug("no bytes read? trying again.");
          continue;
      }
      processFrame(b);
  }
  </code></pre>
  
  <p>If I cycle the 3g on the phone, it works fine. Sometimes it gets into this weird state.</p>
  
  <p><strong>Question</strong></p>
  
  <p>Am I doing something wrong? Is this the <em>expected</em> behavior? Is there existing code I could look at to show the <em>right</em> way to do socket programming on Android?</p>