BufferedReader readLine() blocks

蓝咒 提交于 2019-11-28 11:07:32

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.

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()

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);
}

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

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.

OmarSSelim

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();

.....

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();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!