title: Most efficient way to read in a tcp stream in Java
body: <p>I'm having to modify some client side code because the comms protocol wasn't defined properly.</p>
  
  <p>I'd assummed that a tcp message from the server would terminate in a new line so I used reader.readLine() to read my Data.</p>
  
  <p>Now I've been told that this is not the case and that instead the first 4 chars of the message are the message length and then I have to read the rest of the message.</p>
  
  <p>What is the most efficient sensible way to do this?</p>
  
  <p>my general Idea was as follows:</p>
  
  <ol>
  <li>Create a 4 char array</li>
  <li>Read in first 4 characters</li>
  <li>Determine what the message length is</li>
  <li>Create a new array of message length</li>
  <li>read into the new array.</li>
  </ol>
  
  <p>Here is an example of the code (reader is a BufferedReader created elsewhere): </p>
  
  <pre><code>char[] chars = new char[4];
  int charCount = reader.read(chars);
  String messageLengthString = new String(chars);
  int messageLength = Integer.parseInt(messageLengthString);
  chars = new char[messageLength];
  charCount = reader.read(chars);
  if (charCount != messageLength)
  {
      // Something went wrong...
  }
  </code></pre>
  
  <p>I know how to do this, but Do I have to worry about the character buffers not being filled? if so how should I deal with this happening?</p>