Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading what's available from Socket without blocking

Tags:

java

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.

like image 849
vidit Avatar asked Nov 26 '11 09:11

vidit


1 Answers

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);
}
like image 136
vovahost Avatar answered Oct 22 '22 00:10

vovahost