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:
header = socket.recv(4)
message_length = struct.unpack(">L",header)
message = socket.recv(message_length)
on the Python end.
Java side:
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);
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:
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
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.
out?String, put the message and header into abyte[].