gpt4 book ai didi

java - DataInputStream.read 返回小于 len

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:29 24 4
gpt4 key购买 nike

我正在使用 DataInputStream 从套接字中读取一些字节。我有一个预期的字节数要从流中读取(解码 header 后,我知道消息中有多少字节)它在 99% 的时间内都有效,但偶尔我读取的字节数会小于 len

int numRead = dis.read(buffer, 0, len);

什么会导致 numRead 小于 len?这不是-1。我希望读取的行为会阻塞,直到流关闭或达到 EOF,但如果它是流底层的套接字,除非套接字关闭,否则不应该发生,对吗?

有没有一种从套接字中读取字节的方法总是确保您读取 len 个字节?

谢谢

最佳答案

编辑:对于一般流,基本上,您只需继续阅读,直到阅读完所有想要阅读的内容。对于 DataInput 的实现(例如 DataInputStream),您应该使用 readFully,正如 Peter Lawrey 所建议的那样。考虑这个答案的其余部分与您只有一个 InputStream 的一般情况相关。

对于任何类型的 InputStream 来说,完全为您提供比您要求的更少的数据是合理的,即使更多的数据正在传输中。您应该始终针对这种可能性进行编码 - ByteArrayInputStream 可能是个异常(exception)。 (当然,如果剩余数据少于您请求的数据,那么返回的数据仍然可能比请求的少。)

这是我所说的那种循环:

byte[] data = new byte[messageSize];
int totalRead = 0;

while (totalRead < messageSize) {
int bytesRead = stream.read(data, totalRead, messageSize - totalRead);
if (bytesRead < 0) {
// Change behaviour if this isn't an error condition
throw new IOException("Data stream ended prematurely");
}
totalRead += bytesRead;
}

关于java - DataInputStream.read 返回小于 len,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4673975/

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