I\'m currently writing a Java program that communicates with a Chrome extension. I need to implement the Chrome native messaging protocol in order to communicate. The Google
Chars in Java are automatically transformed into unicode. The correct type for this use case is byte
, which doesn't automatically transform and keeps the correct value. A correct implementation of the Chrome Native Messaging protocol is thus as follows:
public static byte[] getBytes(int length) {
byte[] bytes = new byte[4];
bytes[0] = (byte) ( length & 0xFF);
bytes[1] = (byte) ((length>>8) & 0xFF);
bytes[2] = (byte) ((length>>16) & 0xFF);
bytes[3] = (byte) ((length>>24) & 0xFF);
return bytes;
}
Besides this method, care needs to be used not to use a String anywhere between the calculation of the length-bytes and the output. Output to System.out
can be done as following:
try {
System.out.write(getBytes(message.length()));
} catch (IOException ex) {
ex.printStackTrace();
}