Socket,BufferedReader挂起在readLine()

时间:2011-05-13 06:18:17

标签: java sockets io bufferedreader

我有一台服务器最初这样做: -

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

稍后它将套接字传递给另一个类“foo” 该类等待特定于应用程序的消息。

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

我的客户端发送此序列:

  • “栏\ n” 个
  • “你好吗?\ n”
  • “\ n” 个
  • “将其传递给foo \ n”
  • “\ n” 个

问题是有时“foo”没有得到它的回应。它挂在readLine()

服务器中的readLine()使用提前读取缓存数据的可能性是多少,“foo”类正在变得饥饿?

如果我在客户端添加睡眠,它可以工作。但它永远有效的可能性是什么?

  • “栏\ n” 个
  • “你好吗?\ n”
  • “\ n” 个
  • sleep(1000);
  • “将其传递给foo \ n”
  • “\ n” 个

如何解决问题?感谢这方面的任何帮助。

4 个答案:

答案 0 :(得分:21)

eee的解决方案非常有效。我试图从SMTP会话中读取输出,但它会阻止:

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

更改为:

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

我可以读完一切就好了。 br是BufferedReader对象,BTW。

答案 1 :(得分:2)

第一个BufferedReader中已有数据(已从套接字中读取,并且套接字中不再提供),因此将第一个示例中创建的BufferedReader传递给该类它读取特定于应用程序的消息,而不是从套接字创建新的BufferedReader

答案 2 :(得分:1)

答案可能太迟了,但这是2020年最简单和最新的答案,只需使用简单的方法即可使用输入流read()方法从套接字服务器或客户端接收数据。

客户端断开连接或服务器关闭连接时,将抛出

EOFException

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

答案 3 :(得分:0)

我遇到了同样的问题,这是我的解决方案:

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