如何将字节数组从服务器(码头服务器)发送到客户端(RPI)?
How to send byte array from server(jetty server) to client(RPI)?
我正在尝试将数据字节从服务器发送到客户端,因此我使用文件指针指向文件已读取和读取字节集的位置并将其发送到客户端。
下面是服务器端
byte[] b = readByte()// my function which return bytes of Data
ServletOutputStream stream = httpServletResponse.getOutputStream();
stream.flush();
stream.write(b);
stream.flush();
下面是客户端
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);
以上代码适用于 20Kb 的 bufferLength,随着 bufferLength 的增加,我收到不正确的值。
鉴于您已阐明服务器和客户端就要传输的字节数达成一致,用 bufferLength
表示,您认为他们不需要交换该长度是对的。
但客户端确实需要正确使用该长度。您的问题出在客户端的读取循环中:
int pos = 0;
byte[] b = new byte[buffLength];
while (pos != -1) {
pos = is.read(b, pos, b.length - pos);
}
这有一个明确的和一个潜在的主要问题:
您的接收代码在循环的第三次和后续迭代中(当执行了那么多次迭代时)没有正确填充目标数组,因为 pos
仅记录字节数在最近的 previous read()
中收到。您需要使用 all 之前读取到数组中的字节总数,以确定要尝试读取的偏移量和字节数。
InputStream.read()
将 return -1
仅在 流 的末尾,这通常不会发生在网络流,直到远端关闭。如果服务器在写入数组后没有从其端关闭连接(至少是输出端),那么客户端将挂起尝试读取它。特别是,如果 pos
等于 b.length
,它将进入一个紧密循环,因此请求的字节数为 0。
我正在尝试将数据字节从服务器发送到客户端,因此我使用文件指针指向文件已读取和读取字节集的位置并将其发送到客户端。
下面是服务器端
byte[] b = readByte()// my function which return bytes of Data
ServletOutputStream stream = httpServletResponse.getOutputStream();
stream.flush();
stream.write(b);
stream.flush();
下面是客户端
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);
以上代码适用于 20Kb 的 bufferLength,随着 bufferLength 的增加,我收到不正确的值。
鉴于您已阐明服务器和客户端就要传输的字节数达成一致,用 bufferLength
表示,您认为他们不需要交换该长度是对的。
但客户端确实需要正确使用该长度。您的问题出在客户端的读取循环中:
int pos = 0; byte[] b = new byte[buffLength]; while (pos != -1) { pos = is.read(b, pos, b.length - pos); }
这有一个明确的和一个潜在的主要问题:
您的接收代码在循环的第三次和后续迭代中(当执行了那么多次迭代时)没有正确填充目标数组,因为
pos
仅记录字节数在最近的 previousread()
中收到。您需要使用 all 之前读取到数组中的字节总数,以确定要尝试读取的偏移量和字节数。InputStream.read()
将 return-1
仅在 流 的末尾,这通常不会发生在网络流,直到远端关闭。如果服务器在写入数组后没有从其端关闭连接(至少是输出端),那么客户端将挂起尝试读取它。特别是,如果pos
等于b.length
,它将进入一个紧密循环,因此请求的字节数为 0。