如何在java中实现chrome本机消息传递消息处理协议

我尝试在java中实现本机消息传递协议,但它不起作用。
我尝试了以下方式。

private String readMessage() { int length = getInt(getLength()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); byte[] b = new byte[4]; try { int total; for(int totalRead = 0 ; totalRead < length ; totalRead = totalRead + 4){ System.in.read(b); // make sure bOut.write(b); } } catch (IOException e) { e.printStackTrace(); } String bRes = null; try { bRes = new String(bOut.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return bRes; } 

要读取大小,我使用了以下方法:

这从前四个字节构造int

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

这将读取前四个字节并返回字节数组

 private byte[] getLength() { int length = 0 ; byte[] bytes = new byte[4]; try { System.in.read(bytes); } catch (IOException e) { e.printStackTrace(); } return bytes; } 

这给出了“与本机消息传递主机通信时出错”错误。 如何在java中正确实现此协议。
有人可以为java提供简单的工作示例

我的下面的方法提供了一个Java实现,它从Chrome应用程序接收消息并发回消息。 在我的小端机器上它可以工作。

我没有正确地研究你的努力,但希望这将有助于您的“简单工作示例”请求。

要点:与标准流进行通信。 如您所知,分别读取前4个字节以了解长度(此处为lengthByte):

 byte[] lengthByte = new byte[4]; int bytesRead = System.in.read(lengthByte,0,4); //Read the message into byte[] c: byte[] c = new byte[text_length]; int lengthAppMessage = System.in.read(c,0,text_length); 

回写应用程序时,我们在前4个字节中写入消息长度。 对于消息{"m":"hi"} ,这是我在下面发送的消息,消息长度是10.(对于{"m":"hello"}它是13,等等)

 int returnedMessageLength = 10; System.out.write((byte) (returnedMessageLength)); System.out.write((byte)0); System.out.write((byte)0); System.out.write((byte)0); 

最后三行填充总和为4个字节。 您可能需要在消息长度之前将这三行放入流中。

附加消息时,需要{"...":"..."}格式。 我们可以通过以下部分发送消息:

 System.out.append('{'); System.out.append('"'); System.out.append('m'); System.out.append('"'); System.out.append(':'); System.out.append('"'); System.out.append('h'); System.out.append('i'); System.out.append('"'); System.out.append('}'); 

重点是将消息分成几个部分并分别发送每个部分环绕Java格式化问题(由单个外部引号引起)。

将所有上述代码放在一个永无止境的’while’循环中,以避免过早退出。 (要查看此代码是否正在运行,我将其与Google的本机消息传递页面中的示例集成。)

这不是我使用的好代码,但无论是偶然还是设计,它都是这样的。

以下代码适用于我。

 //Convert length from Bytes to int public static int getInt(byte[] bytes) { return (bytes[3] << 24) & 0xff000000| (bytes[2] << 16)& 0x00ff0000| (bytes[1] << 8) & 0x0000ff00| (bytes[0] << 0) & 0x000000ff; } // Read an input from Chrome Extension static public String receiveMessage(){ byte[] b = new byte[4]; try{ System.in.read(b); int size = getInt(b); byte[] msg = new byte[size]; System.in.read(msg); // make sure to get message as UTF-8 format String msgStr = new String(msg, "UTF-8"); return msgStr; }catch (IOException e){ e.printStackTrace(); return null; } }