Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you make BufferedReader.readLine() not hang?

Is there a way to make BufferedReader.readLine() not hang?

I'm creating a server that:

  • Checks if the client has delivered any input.
  • If not, it executes other code and eventually loops back to checking the client for input.

How can I check if the client has delivered any input without running readLine()? If I run readLine(), the thread will hang until input is delivered?

like image 387
Cin316 Avatar asked Mar 19 '13 21:03

Cin316


1 Answers

You can use BufferedReader.ready(), like this:

BufferedReader b = new BufferedReader(); //Initialize your BufferedReader in the way you have been doing before, not like this.

if(b.ready()){
    String input = b.readLine();
}

ready() will return true if the source of the input has not put anything into the stream that has not been read.

Edit: Just a note, ready will return true whenever even only one character is present. You can use read() to check if there is a line feed or carriage return, and those would indicate an end of line.

For more info: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#ready()

like image 198
Cin316 Avatar answered Oct 14 '22 00:10

Cin316