Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader readLine() blocks

When receiving data using readLine(), even though I put a "\n" at the end of the message using the .flush when sending the message, the while loop that reads my message still blocks. Only when closing the socket connection, it leaves the loop.

Here's the client code :

bos = new BufferedOutputStream(socket.
            getOutputStream());
bis = new BufferedInputStream(socket.
            getInputStream());
osw = new OutputStreamWriter(bos, "UTF-8");
osw.write(REG_CMD + "\n");
osw.flush();

isr = new InputStreamReader(bis, "UTF-8");
BufferedReader br = new BufferedReader(isr);

String response = "";
String line;

while((line = br.readLine()) != null){
   response += line;
}

and the server's code:

BufferedInputStream is;
BufferedOutputStream os;

is = new BufferedInputStream(connection.getInputStream());
os = new BufferedOutputStream(connection.getOutputStream());

isr = new InputStreamReader(is);

String query= "";
String line;

while((line = br.readLine()) != null){
   query+= line;
}

String response = executeMyQuery(query);
osw = new OutputStreamWriter(os, "UTF-8");

osw.write(returnCode + "\n");
osw.flush();

My code blocks at the server while loop. Thanks.

like image 784
Majid Avatar asked Mar 20 '13 10:03

Majid


People also ask

What does BufferedReader readLine do?

Class BufferedReader. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

How many lines can BufferedReader read?

The readLine() method of BufferedReader class in Java is used to read one line text at a time.

Does readLine read empty lines?

It returns "\n" when the line is blank. This is because the line contains an end of line character (it can't contain absolutely nothing.) You can also make your code more robust by doing tokenizer. hasMoreTokens().

What is difference between BufferedReader and InputStreamReader?

BufferedReader reads a couple of characters from the Input Stream and stores them in a buffer. InputStreamReader reads only one character from the input stream and the remaining characters still remain in the streams hence There is no buffer in this case.


1 Answers

The BufferedReader will keep on reading the input until it reaches the end (end of file or stream or source etc). In this case, the 'end' is the closing of the socket. So as long as the Socket connection is open, your loop will run, and the BufferedReader will just wait for more input, looping each time a '\n' is reached.

like image 130
Sinkingpoint Avatar answered Sep 27 '22 20:09

Sinkingpoint