Majid
Majid

Reputation: 664

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.

Upvotes: 14

Views: 55018

Answers (7)

vovahost
vovahost

Reputation: 35997

I tried a lot of solutions but the only one not blocking the execution was the following:

BufferedReader inStream = new BufferedReader(new InputStreamReader(yourInputStream));
String line;
while(inStream.ready() && (line = inStream.readLine()) != null) {
    System.out.println(line);
}

The inStream.ready() returns false if the next readLine() call will block the execution.

Upvotes: 14

Vladislav Kysliy
Vladislav Kysliy

Reputation: 3736

It'd be better avoid using readline(). This method is dangerous for network communications because some servers don't return LF/CR symbols and your code will be stuck. When you read from a file it isn't critical because you will reach end of the file anyway and stream will be closed.

public String readResponse(InputStream inStreamFromServer, int timeout) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inStreamFromServer, Charsets.UTF_8));
    char[] buffer = new char[8092];
    boolean timeoutNotExceeded;
    StringBuilder result = new StringBuilder();
    final long startTime = System.nanoTime();
    while ((timeoutNotExceeded = (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) < timeout))) {
        if (reader.ready()) {
            int charsRead = reader.read(buffer);
            if (charsRead == -1) {
                break;
            }
            result.append(buffer, 0, charsRead);
        } else {
            try {
                Thread.sleep(timeout / 200);
            } catch (InterruptedException ex) {
                LOG.error("InterruptedException ex=", ex);
            }
        }
    }
    if (!timeoutNotExceeded) throw new SocketTimeoutException("Command timeout limit was exceeded: " + timeout);

    return result.toString();
}

It has a timeout and you can interrupt communication if it take a lot of time

Upvotes: 2

Ado
Ado

Reputation: 421

readline() and read() will be blocked while socket doesn't close. So you should close socket:

Socket.shutdownInput();//after reader
Socket.shutdownOutput();//after wirite

rather than Socket.close();

Upvotes: 0

Mehdi
Mehdi

Reputation: 1477

This happens because the InputStream is not ready to be red, so it blocks on in.readLine() . Please try this :

boolean exitCondition= false;

while(!exitCondition){
    if(in.ready()){
        if((line=in.readLine())!=null){
            // do whatever you like with the line
        }
    }
}

Of course you have to control the exitCondition .

An other option can be the use of nio package, which allows asynchronised (not blocking) reading but it depend on your need.

Upvotes: 1

OmarSSelim
OmarSSelim

Reputation: 41

if you want to get what's in the socket without being forced to close it simply use ObjectInputStream and ObjectOutputStream ..

Example:

ObjectInputStream ois;
ObjectOutputStream oos;

ois = new ObjectInputStream(connection.getInputStream());

String dataIn = ois.readUTF(); //or dataIn = (String)ois.readObject();

oos = new ObjectOutputStream(connection.getOutputStream());
oos.writeUtf("some message"); //or use oos.writeObject("some message");
oos.flush();

.....

Upvotes: 0

El Hocko
El Hocko

Reputation: 2606

This is because of the condition in the while-loop: while((line = br.readLine()) != null)

you read a line on every iteration and leve the loop if readLine returns null.

readLine returns only null, if eof is reached (= socked is closed) and returns a String if a '\n' is read.

if you want to exit the loop on readLine, you can omit the whole while-loop und just do:

line = br.readLine()

Upvotes: 3

Sinkingpoint
Sinkingpoint

Reputation: 7624

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.

Upvotes: 23

Related Questions