首页 > 解决方案 > 与本机消息传递主机 - Java 通信时出错

问题描述

所以我正在学习使用 Java 的带有 chrome 扩展的本地消息传递。测试应用程序时出现以下错误:与本机消息传递主机通信时出错。我不确定是什么问题或如何跟踪错误。 这是我的 checker.bat 文件:

@echo off
javac Test.java
java Test

这是清单.JSON:

{
  "name": "host1",

  "description": "Test",
  "path": "checker.bat",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://eogmgkhgmdjkdhkfacckkjhmffnniiab/"
  ]
}

公共类测试{

public static void main(String[] args) {
    Test t=new Test();
    String to_process_string="";
    try {
        to_process_string = t.readMessage(System.in);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String final_output;
    String output=to_process_string+" recieved";
    final_output="{\"m\":\""+output+"\"}";
    try {
        t.sendMessage(final_output);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private String readMessage(InputStream in) throws IOException {
    byte[] b = new byte[4];
    in.read(b);

    int size = getInt(b);

    if (size == 0) {
      throw new InterruptedIOException("Blocked communication");
    }

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

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

  private void sendMessage(String message) throws IOException {
    System.out.write(getBytes(message.length()));
    System.out.write(message.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;
  }

} 我不太确定可能是什么问题你能帮我吗?注意:这是我注册密钥的方式: REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\host1" /ve /t REG_SZ /d "C:\Users\Rex\Desktop\TestNative\Host\manifest.json" /F

编辑:所以我尝试了 WoXxo 在评论中建议的 JSON 格式,但它仍然给了我同样的错误。我决定将问题记录到文件中,但没有任何记录,所以我决定连接保持主函数为空,看看是代码问题还是连接问题。事实证明,它一直给我同样的结果。知道可能是什么问题吗?

标签: javascriptjavagoogle-chrome-extension

解决方案


推荐阅读