Java native messaging with chrome extension - cannot correctly write length

谁说胖子不能爱 提交于 2019-11-30 15:22:44

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();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!