Java native messaging with chrome extension - cannot correctly write length

前端 未结 1 1925
花落未央
花落未央 2021-01-03 01:51

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

相关标签:
1条回答
  • 2021-01-03 02:24

    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();
        }
    
    0 讨论(0)
提交回复
热议问题