InputStream.available()不起作用 [英] InputStream.available() doesn't work

查看:393
本文介绍了InputStream.available()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用inputstream.available()来检查是否有任何要读取的数据而不阻塞线程.但它永远不会返回任何> 0的值.我使用的是错误的吗?

I am trying to use inputstream.available () to check if there is any data to read without blocking the thread. but it never return any value > 0. am I using it wrong?

while (slept < logOnTimeOut) {
    if ( sslSocket.getInputStream().available() > 0 )  {
        if (input.readLine().equals("OK") ) {    // todo: set timeout here
            System.out.println("Successfully Logged On");
            isLoggedOn = true;
            return true;
        }
    } else {
        Thread.sleep(500);
        slept += 500;
    }
}

推荐答案

阅读

返回一个估计值,该估计值可以从此输入流读取(或跳过)而不会被下一次对此输入流的方法的调用所阻塞.下一个调用可能是同一线程或另一个线程.一次读取或跳过这么多字节不会阻塞,但可能会读取或跳过更少的字节.

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

请注意,尽管InputStream的某些实现将返回流中的字节总数,但许多实现则不会.使用此方法的返回值分配旨在保留该流中所有数据的缓冲区永远是不正确的.

简而言之,InputStream.available()的实用性不如您想象的一半.

In short, InputStream.available() is not half as useful as you think it is.

如果您需要检测流的末尾,请从流中查找read(),并检测结果是否为-1.请勿使用available().

If you need to detect the end of the stream, read() from it and it detect if the result is -1. Do not use available().

这篇关于InputStream.available()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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