简体   繁体   中英

Socket, BufferedReader hangs at readLine()

I have a server which initially does this:-

BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
for (;;) {
  String cmdLine = br.readLine();
  if (cmdLine == null || cmdLine.length() == 0)
     break; 
  ...
}

later it passes the socket to another class "foo" This class wait for application specific messages.

 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
 appCmd=br.readLine();

My client sends this sequence:

  • "bar\\n"
  • "how are u?\\n"
  • "\\n"
  • "passing it to foo\\n"
  • "\\n"

The problem is that sometimes "foo" does not get its response. It hangs in the readLine() .

What is the chance that readLine() in the server is buffering up the data using the read ahead and "foo" class is getting starved?

If I add a sleep in the client side, it works. But what is the chance that it will always work?

  • "bar\\n"
  • "how are u?\\n"
  • "\\n"
  • sleep(1000);
  • "passing it to foo\\n"
  • "\\n"

How to fix the problem? Appreciate any help on this regard.

eee's solution works perfectly. I was trying to read output from an SMTP conversation but it would block on:

while ((response = br.readLine()) != null) {
    ...Do Stuff
}

Changing to:

while (br.ready()) {
    response = br.readLine();
    ...Do Stuff
}

I can read everything just fine. br is a BufferedReader object, BTW.

I had the same problem and here is my solution:

try {
    StringBuilder response = new StringBuilder();
    response.append("SERVER -> CLIENT message:").append(CRLF);
    //Infinite loop
    while (true) {
        //Checks wheather the stream is ready
        if (in.ready()) {
            //Actually read line 
            lastLineFromServer = in.readLine();
            //If we have normal behavior at the end of stream
            if (lastLineFromServer != null) {
                response
                        .append(lastLineFromServer)
                        .append(CRLF);
            } else {
                return response.toString();
            }
        } else {//If stream is not ready
            //If number of tries is not exceeded
            if (numberOfTry < MAX_NUMBER_OF_TRIES) {
                numberOfTry++;
                //Wait for stream to become ready
                Thread.sleep(MAX_DELAY_BEFORE_NEXT_TRY);
            } else {//If number of tries is exeeded
                //Adds warning that things go weired
                response
                        .append("WARNING \r\n")
                        .append("Server sends responses not poroperly.\r\n")
                        .append("Response might be incomplete.")
                        .append(CRLF);
                return response.toString();
            }
        }
    }
} catch (Exception ex) {
    ex.printStackTrace();
    return "";
}

第一个BufferedReader已经有数据(已从套接字读取,不再从套接字中可用),因此将第一个示例中创建的BufferedReader传递给读取应用程序特定消息的类,而不是创建一个来自套接字的新BufferedReader

The answer might be late but this is the simplest and latest answer in 2020, just use the simple way to receive the data from the socket server or client using the input stream read() method.

EOFException will be thrown when the client is disconnected or the server closed the connection.

private String waitForData() throws IOException {
    String data = "";
    do {
        int c = inputStream.read();
        if (c > -1) data += (char) c;
        else throw new EOFException();
    } while (inputStream.available() > 0);
    return data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM