title: android - how to read a specific number of bytes from socket?
body: <p>In my system, I am using tcp to transfer messages between an android application, and a desktop application (that is developed in Qt).</p>
  
  <p>I am using <code>msgpack</code> library to serialize/deserialize structures in both applications. In order to make sure that the structure is always received as a whole, I always send the number of bytes (encoded as a 32-bit big endian unsigned integer not using <code>msgpack</code> so that it always takes the first 4 bytes) before the message itself (that is encoded in <code>msgpack</code>). If there is a better way please tell me.</p>
  
  <p>In the android app, I read the first 4 bytes into a <code>byte[]</code> and decode it into a <code>long msgSize</code>, next I need a way for the thread to keep blocking until the next <code>msgSize</code> bytes are received. After reading other questions and answers, I think I can write something like this:</p>
  
  <pre><code>InputStream is= sock.getInputStream();
  byte[] msgSizeBuff= new byte[4];
  is.read(msgSizeBuff, 0, 4);
  long msgSize= MyDecodeFunction(msgSizeBuff);
  DataInputStream dis = new DataInputStream(is);
  byte[] msg = new byte[msgSize];
  dis.readFully(msg);
  </code></pre>
  
  <p>After that I can use the msg array with msgpack, and I am sure that the whole message is received.</p>
  
  <p>So:</p>
  
  <ol>
  <li>is my usage of <code>DataInputStream</code> class alright, and am I guranteed that I will wait until I receive the specified number of bytes? because in the <a href="http://developer.android.com/reference/java/io/DataInputStream.html" rel="nofollow">reference</a> they say:</li>
  </ol>
  
  <blockquote>
    <p>If insufficient bytes are available, EOFException is thrown.</p>
  </blockquote>
  
  <ol start="2">
  <li>I want a way to tell this thread to cancel the operation, so what would happen if another thread calls <code>socket.close()</code> or <code>socket.shutdownInput()</code>, will I get an exception?</li>
  </ol>