gpt4 book ai didi

java - 如何从服务器(jetty服务器)发送字节数组到客户端(RPI)?

转载 作者:行者123 更新时间:2023-12-02 11:14:56 26 4
gpt4 key购买 nike

我正在尝试从服务器向客户端发送数据字节,因此我使用文件指针来指向文件已读取的位置并读取字节集并将其发送到客户端。

下面是服务器端

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 表示)有共同协议(protocol),因此您认为他们不需要交换该长度是正确的。

但是客户端确实需要使用正确的长度。您的问题出在客户端的读取循环中:

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

这有一个明确的和一个潜在的主要问题:

  1. 您的接收代码在循环的第三次及后续迭代中(执行多次迭代时)无法正确填充目标数组,因为 pos 仅记录接收到的字节数在最近的前一个 read() 中。您需要使用截至该点之前所有读取到数组中的总字节数来确定偏移量和尝试读取的字节数。

  2. InputStream.read() 仅在末尾返回 -1,这通常不会发生在网络流,直到远端关闭。如果服务器在写入数组后没有从一端关闭连接(至少是输出端),那么客户端将在尝试读取它时挂起。特别是,如果pos等于b.length,则会进入紧密循环,从而请求的字节数为0。

关于java - 如何从服务器(jetty服务器)发送字节数组到客户端(RPI)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50351831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com