我正在使用 Chrome 的 Native Messaging API 将数据传递到我的 Java 主机。该数据是一个以 Base64 编码的 512 KB 长字符串。问题在于主机从标准输入读取数据所需的时间太长。 我读了以下帖子:Very Slow to pass "large" amount of data from Chrome Extension to Host (written in C#)我知道问题在于我如何读取字节,但到目前为止我无法将该代码适应 java。
我的主机代码是:
try {
// hilo principal de la aplicacion
while(true){
int length = 0;
String input = "";
String output = "";
String outputType = "";
// cargamos la logitud de caracteres en bytes
byte[] bytes = new byte[4];
System.in.read(bytes, 0, 4);
length = getInt(bytes);
// cargamos los datos enviados
byte[] data = new byte[length];
System.in.read(data, 0, length);
if (length == 0){
// si no recibimos datos ponemos un sleep para no comer todos los recursos del equipo
Thread.sleep(50);
break;
}else{
// Loop getchar to pull in the message until we reach the total length provided.
for (int i=0; i < length; i++){
input += (char) data[i];
}
// leemos el texto enviado del dato en JSON
JSONObject obj = new JSONObject(input);
String texto = obj.getString("text");
System.err.write(("TEXT: " + texto).getBytes());
// creamos el mensaje de respuesta y lo enviamos
String respuesta = "{\"type\":\"TEST\", \"text\":\"" + texto + "\"}";
System.out.write(getBytes(respuesta.length()));
System.out.write(respuesta.getBytes(Charset.forName("UTF-8")));
}
}
} catch (Exception e) {
e.printStackTrace();
}
我需要帮助来调整我的主机的 java 代码以快速读取消息。
最佳答案
- 您可以使用
DataInputStream.readInt()
和.readFully()
完成大部分工作,并且不会出现错误。如果您使用的是 Intel,则需要重新排列 int 以适应 native 字节顺序,因为这会读取网络字节顺序。 - 在它和
System.in
之间放置一个BufferedInputStream
:这将解决主要的性能问题。 - 通过
new String(data,...)
而不是附加循环解决其他性能问题。 - 很难理解为什么他们会给你发送零长度,但如果他们这样做, sleep 除了浪费时间之外不会有任何效果。删除它。
关于java - 针对更大的字符串优化 Java 中的 native 消息主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900054/