套接字,BufferedReader 挂在 readLine() [英] Socket, BufferedReader hangs at readLine()

查看:23
本文介绍了套接字,BufferedReader 挂在 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; 
  ...
}

稍后它将套接字传递给另一个类foo"此类等待特定于应用程序的消息.

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:

  • "条 "
  • 你好吗? "
  • " "
  • 将它传递给 foo "
  • " "
  • "bar "
  • "how are u? "
  • " "
  • "passing it to foo "
  • " "

问题是有时foo"没有得到它的响应.它挂在 readLine() 中.

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

服务器中的 readLine() 使用预读缓冲数据并且foo"类变得饥饿的可能性有多大?

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?

  • "条 "
  • 你好吗? "
  • " "
  • sleep(1000);
  • 将它传递给 foo "
  • " "
  • "bar "
  • "how are u? "
  • " "
  • sleep(1000);
  • "passing it to foo "
  • " "

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

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

推荐答案

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

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
}

更改为:

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

我可以很好地阅读所有内容.br 是一个 BufferedReader 对象,顺便说一句.

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

这篇关于套接字,BufferedReader 挂在 readLine()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆