Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

java - InputStream.available() doesn't work

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Read the 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.

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

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...