java - 在什么情况下读取 InputStream.read() 返回正整数,什么时候返回 -1?

标签 java stream network-programming

我对 InputStream.read() 的工作方式有一些疑问。我正在尝试监听 InputStream ,每当字节可用时,我需要将它们复制到字节数组,然后将字节数组传递给另一个方法以进行进一步处理,然后返回监听到输入流以获取下一组字节。这是我已经走了多远:

while(true){
    while((i = inputstream.read(recvBuffer, 0, recvBuffer.length)) != -1){
    doSomething(recvBuffer);
    }
}

我读到 read(byte[] b, int off, int len) 方法返回一个 int ,它应该表示从流中读取的字节数。这是否意味着只要字节可用,它就会将 i 的值设置为相应的字节数?一旦它读取x个字节并到达流的末尾,它不是会返回一个表示字节数的正整数,而不是-1吗?那么,什么时候会对 i 进行针对 -1 的检查呢?我知道我的解释是错误的,但我不能说怎么解释。任何帮助理解这一点的帮助将不胜感激

此外,我知道发送者可以推送到流上的最大字节数。在这种情况下,将 recvBuffer 的大小指定为最大字节数是否足够,或者分配多一点是否明智?

最佳答案

doSomething(recvBuffer);

应该是这样

doSomething(recvBuffer, i);

该方法需要知道实际收到了多少字节。

I read that read(byte[] b, int off, int len) method returns an int that is supposed to represent the number of bytes read from the stream.

正确。

Doesn't that mean whenever bytes are available, it sets the value of i to the respective number of bytes?

是的。

Once it reads x number of bytes and reaches the end of the stream, wouldn't it return a positive integer representing the number of bytes, instead of -1?

不,它传输字节并返回计数,然后下次没有字节,只有流结束,因此返回-1。

Then, when would the check against -1 happen for i? I know I'm interpreting this wrong but I can't say how.

见上文。

Also, I know the max amount of bytes that a sender can push onto a stream. In this case, is it sufficient to specify the size of recvBuffer as the max amount of bytes or is it prudent to allocate a bit more than that?

大多数人使用 4096 或 8192 字节。事实上,指定一个大于路径 MTU 的缓冲区并没有多大意义,路径 MTU 通常小于 1500,除非您读取速度很慢,以致内核套接字接收缓冲区被填满。

关于java - 在什么情况下读取 InputStream.read() 返回正整数,什么时候返回 -1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521284/

相关文章:

Java 字节码子例程 - 无法加载返回地址

c# - Stream.Copy 是否通过管道传输?

java - 使用java获取网络利用率

c# - 使用httpClient同步下载文件

java - 如何使用 Glassfish 2.1 在 JPA 中实现悲观锁定?

java - 更改 Spring 事务中的隔离级别

java - 如何向企业解释为什么重构很重要

c++ - 将 std::left 作为参数传递

audio - 使用Red5媒体服务器播放音频

android - 改造@Url 不会覆盖 BaseUrl