title: How can I send a 4 byte header from Java and read it in Python?
body: <p>I am trying to send a message via TCP sockets from a Java application and read it in Python 2.7
  I want the first 4 bytes to specify the message length, so I could do:</p>
  
  <pre><code>header = socket.recv(4)
  message_length = struct.unpack("&gt;L",header)
  message = socket.recv(message_length)
  </code></pre>
  
  <p>on the Python end.</p>
  
  <p>Java side:</p>
  
  <pre><code>out = new PrintWriter(new BufferedWriter(new StreamWriter(socket.getOutputStream())),true);
  byte[] bytes = ByteBuffer.allocate(4).putInt(message_length).array();
  String header = new String(bytes, Charset.forName("UTF-8"));
  String message_w_header = header.concat(message);
  out.print(message_w_header);
  </code></pre>
  
  <p>This works for some message lengths (10, 102 characters) but for others it fails (for example 1017 characters). In the case of failing value if I output the values of each bytes I get: </p>
  
  <pre><code>Java:
  Bytes 0 0 3 -7
  Length 1017
  Hex string 3f9
  
  Python:
  Bytes 0 0 3 -17
  Length 1007
  Hex string \x00\x00\x03\xef
  </code></pre>
  
  <p>I think this has something to do with signed bytes in Java and unsigned in Python but I can't figure out what should I do to make it work.</p>