Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 "
  • "how are u? "
  • " "
  • "passing it to foo "
  • " "

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 "
  • "how are u? "
  • " "
  • sleep(1000);
  • "passing it to foo "
  • " "

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
882 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...