套接字:BufferedReader readLine()块 [英] Sockets: BufferedReader readLine() blocks

查看:96
本文介绍了套接字:BufferedReader readLine()块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BufferedReader.readLine()方法从远程服务器读取响应(用C编写,我无法访问源代码)。 / p>

I am using BufferedReader.readLine() method to read a response from a remote server (which is written in C and I have no access to source code).

BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while((line = br.readLine())!=null){
    [...]
}

但它总是在最后一行阻塞,直到它超时。所以我使用了以下代码:

But it always blocks at the last line until it times out. So I used the following code:

int b;
while(true){
   b = in.read;
   [...]
}

我发现最后一个byte read的整数值是13,我认为它是一个回车符,对吗?

and I found out that the last byte read has an integer value of 13, which I think it is a carriage return, right?

那么为什么 readLine 方法块?服务器通常如何发出信号流的结束信号?谢谢。

So why the readLine method blocks? How does the server usually signal an end of stream is reached? Thanks.

推荐答案

如果是网络连接,则在套接字关闭时终止流。

In the case of a network connection, the stream is terminated when the socket is closed.

因此, readLine()阻止它收到行尾或你关闭是完全正常的手动连接。当 readLine()收到带有'13'值的最后一个字符时,将读取该行并再次开始循环,等待下一行。

So it is perfectly normal that readLine() blocks until it received an "end of line" or you close manually the connection. When your readLine() receives the last character with the '13' value, the line is read and the loop starts again, waiting for the next line.

最后一行与其他行没有区别。

There is no difference between the "last line" and the other lines.

为了停止循环,你必须手动关闭某处的连接或等待超时。但是如果没有关于你的通信协议的更多信息,就不可能更加准确。

In order to stop the loop, you must manually close the connection somewhere or wait for the timeout. But without more information about your communication protocol, it is impossible to be more precise about this.

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

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