I am working on a server which reads data sent by the client, but the size is not known neither can I change the client to send the size.
I want to read the data from client till it blocks and waits for server’s response. I tried using available(), it works sometimes but sometimes it just returns zero even when there’s some data in stream.
while((len = in.available()) != 0)
in.read(b,0,len);
Is there any way to do this in Java? I’m aware of asynchronous methods, but have never tried that, so if someone can provide a short example.
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 thatreadwill not block. You must, however, check the value returned byread(the actual number of bytes read into the array):Note that
availablereturning 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.