java - Native Messaging 主机尝试发送长度为 977472013 字节的消息

标签 java google-chrome chrome-native-messaging

我正在使用 java jar 通过 Chrome Native Messaging 发送和接收消息。

我启用了 Chrome 日志记录,以便可以读取 C:\Users\%UserName%\AppData\Local\Google\Chrome\User Data\chrome_debug.log 文件

我实际上无法使用我的 Java 应用程序发送或接收消息,但我知道它已被使用。

这是我的主机的 list :

{
   "allowed_origins" : 
    [ 
        "chrome-extension://EXTENSION-ID/" 
    ],
   "description" : "my.app",
   "name" : "my.app",
   "path" : "launch.bat",
   "type" : "stdio"
}

以下是批处理文件 launch.bat 的内容:

java -jar "%~dp0ChromeSEOConnector.jar"

这是我的 Java 代码:

private String readMessage(InputStream in) throws IOException {
        byte[] b = new byte[4];
        in.read(b);

        int size = getInt(b);

        b = new byte[size];
        in.read(b);

        return new String(b, "UTF-8");
    }

private void sendMessage(String message) throws IOException {
        Text text = new Text(message);
        String resposta = serializer.toJson(text);
        System.out.write(getBytes(resposta.length()));
        System.out.write(resposta.getBytes("UTF-8"));
        System.out.flush();
    }

public int getInt(byte[] bytes) {
        return (bytes[3] << 24) & 0xff000000 |
                (bytes[2] << 16) & 0x00ff0000 |
                (bytes[1] << 8) & 0x0000ff00 |
                (bytes[0] << 0) & 0x000000ff;
    }

 public 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;
    }

似乎 System.in 永远不会获取我的应用程序的输入,并且 System.out 也永远不会发送数据。

Chrome 不断出现相同的错误:

Native Messaging host tried sending a message that is 977472013 bytes long.

奇怪的是,即使我手动更改发送的消息的大小,消息的大小始终相同,就好像消息根本没有被分析一样。你遇到过这样的错误吗?提前致谢

最佳答案

我认为您必须交换定义消息长度的字节顺序。将您的 getBytes() 方法更改为:

public byte[] getBytes(int length) {
    byte[] bytes = new byte[4];
    bytes[3] = (byte) (length & 0xFF);
    bytes[2] = (byte) ((length >> 8) & 0xFF);
    bytes[1] = (byte) ((length >> 16) & 0xFF);
    bytes[0] = (byte) ((length >> 24) & 0xFF);
    return bytes;
}

关于java - Native Messaging 主机尝试发送长度为 977472013 字节的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909282/

相关文章:

javascript - Chrome Native Messaging - 为什么我会收到 "Specified native messaging host not found"错误?

Java SpringBoot Rest OAuth2 主体为空

java - 测试环境中的JPA @PrePersist

javascript - chrome console.log 的别名

javascript - 使用 PHP 的 Chrome native 消息传递

google-chrome - 后台js中的chrome扩展卸载事件

java - Swing - 在运行时更改菜单栏和菜单项字体大小

java - Scala 父类类似于 java 中的父类,即 Java.lang.Object

html - 为什么 Chrome 移动我的表单标签并在选择接收焦点时选择?

javascript - 如何像在 IE 中一样在 Chrome 中禁用 A 超链接