套接字InputStream块在available()/read()上 [英] Socket InputStream blocks on available() / read()

查看:45
本文介绍了套接字InputStream块在available()/read()上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取Socket InputStream,调用read()和available()可以进行几次循环迭代.以后的available()会无限期阻止!

I'm reading Socket InputStream, calling read() and available() works for few looping iterations. Later available() blocks indefinitely!

可能是什么问题?我该如何使其不受阻碍?

What could be the issue? How can I make this non-blocking?

代码:

BufferedInputStream buffIn = new BufferedInputStream(in);
while (true)
{
    if (buffIn.available() > 0)
    {
        len = buffIn.read(buffer, 0, buffer.length);
        if (len == -1)
        {
            break;
        }
        baos.write(buffer, 0, len);
    }
}

推荐答案

它并没有阻止它正在旋转.

It is not blocking it is spinning.

一旦没有可用的数据,您的代码也可能会被读取

Once there is no data available you code might as well read

while (true)
{
    if (buffIn.available() > 0) // ALWAYS false now we've run out of data
    {
       // unreachable
    }
}

循环将永远不会结束.没有可用数据时,将永远不会执行负1值的测试.

The loop will never finish. Your test for the minus 1 value will never be executed when there is no data available.

您会在堆栈跟踪中看到available(),因为这是循环中唯一占用任何时间的东西,因此,当您创建堆栈跟踪时,它就有可能出现.

You are seeing available() in the stack trace because that's about the only thing in your loop that's taking up any time, so the chances are, when you create you stack trace, that's where it's going to be.

如果您确信实际上会得到文件结尾条件(例如,如果是TCP,而另一端关闭了连接),则根本不需要available()调用.否则,您需要另一种方法来确定您是否拥有所有数据.例如,有效载荷大小是在前几个字节中编码的还是类似的?

If you are confident that you will infact get an end-of-file condition (eg if it's TCP and the other end closes the connection) then the available() call is not required at all. Otherwise, you need a different method of determining you have all of the data. For example is the payload size encoded in the first few bytes or something?

这篇关于套接字InputStream块在available()/read()上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆