Reading what's available from Socket without blocking
Using available()
is the only way to do it without resorting to asynchronous methods.
You don't really need to rely on the value returned by available()
; just check that there is "some" data available to make sure that read
will not block. You must, however, check the value returned by read
(the actual number of bytes read into the array):
// Process all data currently available
while (in.available() != 0)
{
int nb = in.read(b);
// Process nb bytes
}
Note that available
returning 0 does not mean that the end of the data was reached -- it merely means that there is no data available for immediate consumption (data may become available in the next millisecond). Thus you'll need to have some other mechanism in order for the server to know that the client will not send any more data and is waiting for a response instead.
InputStream
JavaDocs for the method available()
clearly states that
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.
You should instead try the read()
method to read data into a fixed size buffer allocated with, say 4096 bytes.
I tried a lot of solutions but the only one I found which wasn't blocking execution was:
BufferedReader inStream = new BufferedReader(new InputStreamReader(yourInputStream));
String line;
while(inStream.ready() && (line = inStream.readLine()) != null) {
System.out.println(line);
}