Quantcast
Channel: Library Questions - Processing 2.x and 3.x Forum
Viewing all articles
Browse latest Browse all 2896

Missing some data from a call to readBytes()

$
0
0

Hello,

I'm writing a client/server application and am having some issues with the network library. When a client requests a large amout of data (like an image file) from the server, during the call to readBytes(), it only gets part of the message.

This is an excerpt of the client code for your reference:

if (client.available() > 0)
{
  byte[] chunk = new byte[1024];
  chunk = client.readBytes();
  println("DEBUG: received data length: " + chunk.length);
  String new_string = new String(chunk);
  println("DEBUG: stringified data: " + new_string);
  JSONObject server_response = parseJSONObject(new_string);
}

And here's some of the server code:

File file = new File(filepath);
String encoded_photo = "";
JSONObject server_response = new JSONObject();
byte[] data;
try {
    data = server_response.toString().getBytes("UTF-8");
    println("DEBUG: Size of JSONObject bytes: " + server_response.size());
} catch (java.io.UnsupportedEncodingException e) {
  throw new RuntimeException(e);
}
println("DEBUG: written data length: " + data.length);
thisClient.write(data);

The debug output from the server application would indicate the correct amout of data is being sent:

DEBUG: received data length: 60
DEBUG: received request for image 4459648.png
DEBUG: Loading photo...
DEBUG: Size of encoded image: 2457044
DEBUG: written data length: 2457119

But the debug output from the client seems to indicate that it's not receiving all the data before it starts trying to process it.

DEBUG: received data length: 8806
DEBUG: stringified data: {
  "meetup_chat_id": "4459648",
  "data": "iVBORw0KGgoAAAANSUh...(continues but never is terminated)

When the line String new_string = new String(chunk); runs, about half the time I'll get the full image file saved, but the other half I'll get an "Unterminated String" exception, and the data received size is not the same as the data sent.

How would one go about solving this type of problem? Any suggestions welcome.

Thanks, Marcus


Viewing all articles
Browse latest Browse all 2896

Trending Articles