简体   繁体   English

如何将字节数组从服务器(码头服务器)发送到客户端(RPI)?

[英]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. 上面的代码适用于20Kb的bufferLength,随着bufferLength的增加,我收到了不合适的值。

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. 因为您已经澄清了服务器和客户端在要传输的字节数上有一个共同的协议(由bufferLength表示),所以您不需要交换该长度是正确的。

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() . 您的接收代码无法在循环的第三次和后续迭代中正确填充目标数组(执行多次迭代时),因为pos仅记录最近一次的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. InputStream.read()仅在的末尾返回-1 ,除非关闭远端,否则通常不会在网络流上发生。 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. 特别是,如果pos等于b.length ,它将进入紧密循环,因此请求的字节数为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM