The problem with your implementation is that the write method writes only one byte, see the documentation. An important suggestion here is: "24 high-order bits of b are ignored." Therefore, stream.write(msg.length()); probably doesn't do what is intended. (I assume msg.length () returns an int, correct me if I am wrong here.)
Try writing four bytes of int:
stream.write(msg.length() % 256); stream.write((msg.length() / 256) % 256); stream.write((msg.length() / (256 * 256)) % 256); stream.write((msg.length() / (256 * 256 * 256)) % 256);
This writes the low byte first, you can reorder if you want. You can do the conversion to bytes also with a bit shift, the division looks more clear to me, but this is a matter of personal taste.
source share