- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试在 java 中实现 native 消息传递协议(protocol),但没有成功。
我按照以下方式尝试了它。
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;
}
这给出了“与 native 消息传递主机通信时出错”的错误。我怎样才能在 java 中正确地实现这个协议(protocol)。
有人可以为 java 提供简单的工作示例
最佳答案
我下面的方法提供了一个 Java 实现,它从 Chrome 应用程序接收消息并发回消息。在我的小端机器上它可以工作。
我没有正确研究您的努力,但希望这对您的“简单工作示例”请求有所帮助。
要点:使用标准流进行通信。如你所知,分别读入前4个字节来学习长度(这里,in to 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"}
code> 是 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 本地消息传递页面的示例进行了集成。)
这不是我用过的好代码,但无论是偶然还是设计,它对我来说都是这样工作的。
关于java - 如何在java中实现chrome native messaging消息处理协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32553999/
我是一名优秀的程序员,十分优秀!