java-InputStream.available()不起作用

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

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;
    }
}

解决方法:

阅读javadoc

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.

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

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

如果需要检测流的末尾,请从该流中读取()并检测结果是否为-1.不要使用available().

上一篇:Java套接字:InputStream.read()与BufferedReader.read()


下一篇:java-Kotlin中的错误“必须不为null”