Reputation: 131
I am using Chrome's Native Messaging API to pass data to my host in Java. The data is a 512 KB long String encoded in Base64. The problem is that the Host is taking too long to read the data from the standard input. I read the following post: Very Slow to pass "large" amount of data from Chrome Extension to Host (written in C#) and I understand that the problem is how I read the bytes but I was’nt able to adapt that code to java so far.
The code of my host is:
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();
}
I need help to adapt the code of my host in java to read the message quickly.
Upvotes: 0
Views: 378
Reputation: 310957
DataInputStream.readInt()
and .readFully()
. If you're on an Intel you will need to rearrange the int for native byte order, as this reads network byte order.BufferedInputStream
between that and System.in
: that will solve the major performance problem.new String(data,...)
instead of the appending loop.Upvotes: 1