title: Read binary data from a socket
body: <p>I'm trying to connect to a server, and then send it a HTTP request (GET in this case). The idea is request a file and then receive it from the server. </p>
  
  <p>It should work with both text files and binary files (imgs for example). I have no problem with text files, it works perfect, but I'm having some troubles with binary files.</p>
  
  <p>First, I declare a BufferedReader (for reading header and textfile) and a DataInput Stream:</p>
  
  <pre><code>BufferedReader in_text = new BufferedReader(
      new InputStreamReader(socket.getInputStream()));
  
  DataInputStream in_binary = new DataInputStream(
      new BufferedInputStream(socket.getInputStream()));
  </code></pre>
  
  <p>Then, I read the header with in_text and discover if it's a textfile or binary file. In case it's a textfile, I read it correctly in a StringBuilder. In case it's a binary file, I declare a byte[filesize] and store the following content of in_binary.</p>
  
  <pre><code>byte[] bindata = new byte[filesize];
  in_binary.readFully(bindata);
  </code></pre>
  
  <p>And it doesn't work. I get a EOFException.</p>
  
  <p>I thought that maybe in_binary is still in the first position of the stream, so it hasn't read the header yet. So I captured the length of the header and skip that bytes in in_binary.</p>
  
  <pre><code>byte[] bindata = new byte[filesize];
  in_binary.reset();
  in_binary.skip(headersize);
  in_binary.readFully(bindata);
  </code></pre>
  
  <p>And still the same.</p>
  
  <p>What could be happening?</p>
  
  <p>Thanks!</p>
  
  <p>PD: I know I could use URLConnection and all of that. That's not the problem.</p>