narengs7
narengs7

Reputation: 67

How to send byte array from server(jetty server) to client(RPI)?

I am trying to send bytes of data from server to client, so i am using the file pointer to point to location the file has read and read set of bytes and send it to client.

Below is server side

byte[] b = readByte()// my function which return bytes of Data
ServletOutputStream stream = httpServletResponse.getOutputStream();
stream.flush();
stream.write(b);
stream.flush();

Below is client side

URL url = new URL("http://localhost:1222/?filePointer=" + fp);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
InputStream is = conn.getInputStream();
System.out.println("Connection Open");
int pos = 0;
byte[] b = new byte[buffLength];
while (pos != -1) {
    pos = is.read(b, pos, b.length - pos);
}
write2File(b);

The above code works for bufferLength of 20Kb, as bufferLength is increased I receive improper values.

Upvotes: 0

Views: 446

Answers (1)

John Bollinger
John Bollinger

Reputation: 181169

Inasmuch as you have clarified that the server and client have a common agreement on the number of bytes to transfer, represented by bufferLength, you are right that they do not need to to exchange that length.

But the client does need to use that length correctly. Your problem is in the client's read loop:

int pos = 0;
byte[] b = new byte[buffLength];
while (pos != -1) {
    pos = is.read(b, pos, b.length - pos);
}

There is one definite and one potential major problem with that:

  1. Your receiving code does not populate the destination array correctly on the third and subsequent iterations of the loop (when that many iterations are performed), because pos records only the number of bytes received in the most recent previous read(). You need to use the aggregate number of bytes read in all previous reads into the array up to that point to determine the offset and number of bytes to attempt to read.

  2. InputStream.read() will return -1 only at the end of the stream, which will not normally occur on a network stream until the far end is closed. If the server does not close the connection (at least the output side) from its end after writing the array, then the client will hang trying to read it. In particular, it will go into a tight loop if pos is equal to b.length, so that the number of bytes requested is 0.

Upvotes: 1

Related Questions