简体   繁体   English

BufferedReader ReadLine冻结程序

[英]BufferedReader ReadLine froze the program

My code is as follows; 我的代码如下:

When i use BufferedRead readLine() the whole program gets frozen. 当我使用BufferedRead readLine()时,整个程序被冻结。 the problem is that readLine will rnot return the line until it reaches the end of the line. 问题是readLine不会返回该行,直到到达该行的末尾。 because the server will not send a new line char value it will not close. 因为服务器不会发送新行的char值,所以它不会关闭。

So how can i get over this ? 那么我该如何克服呢? Please edit my code; 请编辑我的代码;

                  while (ok) {
                        BufferedReader re = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        aString = re.readLine();
                        ...
                    }

note: i want to do this programatically, and not go and kill the process that's running it 注意:我想以编程方式执行此操作,而不要终止正在运行它的进程

UPDATE

StringBuilder re= new StringBuilder();
                    while ((c = r.read()) >= 0) {
                            re.append( (char)c ) ;  
                    }
                    String result = re.toString();
                    byte[] contentInBytes = result.getBytes();
                    out.write(contentInBytes);
                    out.flush();
                    out.close();

Don't use the readLine() method of BufferedReader . 不要使用BufferedReader的readLine()方法。 Use the read() method, which will read individual characters. 使用read()方法,该方法将读取单个字符。 You'll have to convert them from ints to characters, but that will get you around not having a newline character to read. 您必须将它们从整数转换为字符,但这将使您不必读取换行符。

EDIT: Adding Assuming "re" is your buffered socket input stream reader... 编辑:添加假设“ re”是您的缓冲套接字输入流阅读器...

while ((i = re.read()) != -1)
{
   if (i > 0)
   {
      char c = (char) i;
      // Do something with the character
   }
}

END EDIT 结束编辑

Additionally if you are concerned about the server not responding, then you may want to place a timeout on the Socket : 另外,如果您担心服务器没有响应,则可能需要在Socket上放置超时:

socket.setSoTimeout(milliseconds);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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