title: DataInputStream readInt() works only once
body: <p>I'm using Java sockets to make two android devices communicating with the same app. The communication protocol is:</p>
  
  <pre><code>1. client sends packet size S
  2. client sends byte array with size S
  </code></pre>
  
  <p>I'm using <code>DataOutputStream</code> and <code>writeInt()</code> to write the size as raw value on the stream. The server then reads this value whit <code>DataInputStream</code> and <code>readInt()</code>.
  The problem is that <code>readInt()</code> reads the right value only for the first packet. The second time this method returns a random <code>int</code>.</p>
  
  <p>Relevant code snippets:</p>
  
  <p>Client side: this method is called on top of a working TCP connection with the server</p>
  
  <pre><code>public void write(byte[] packet)
  {
      try
      {
          dataOutputStream.writeInt(packet.length);
          dataOutputStream.flush();
  
          dataOutputStream.write(packet);
          dataOutputStream.flush();        
      }
      catch (IOException e)
      {
          Log.e(ERROR_TAG, "write() failed", e);
      }
  }
  </code></pre>
  
  <p>Server side: this is the loop that reads data</p>
  
  <pre><code>...
  
  int readBytes = 0;
  int packetSize = 0;
  
  while (true) {
      byte[] buffer = new byte[NET_BUFF_SIZE];
  
      try // first it reads the packet size from packet header
      {
          packetSize = dataInputStream.readInt();
      } catch (IOException e) {
          Log.e(ERROR_TAG, "readInt() failed", e);
          return;
      }
  
      while (readBytes &lt; packetSize) {
          try {
              int readResult = dataInputStream.read(buffer);
  
              if (readResult != -1) {
                  readBytes += readResult;
              } else {
                  break;
              }
          } catch (IOException e) {
              Log.e(ERROR_TAG, "read() failed", e);
              break;
          }
      }
  }
  </code></pre>
  
  <p>So, when the client calls <code>write()</code> to send the second packet, the server reads a wrong size from the stream. </p>
  
  <p><code>DataOutputStream</code> and <code>DataInputStream</code> are initialized in this way:</p>
  
  <pre><code>// Server
  inputStream = clientSocket.getInputStream();
  dataInputStream = new DataInputStream(inputStream);
  
  // Client
  outputStream = socket.getOutputStream();
  dataOutputStream = new DataOutputStream(outputStream);
  </code></pre>
  
  <p>What I am missing?</p>