套接字:BufferedReader readLine() 块
我正在使用 BufferedReader.readLine() 方法从远程服务器读取响应(这是用 C 编写的,我无法访问源代码)。
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while((line = br.readLine())!=null){
[...]
}
但它总是阻塞在最后一行,直到超时。所以我使用了以下代码:
int b;
while(true){
b = in.read;
[...]
}
我发现最后读取的字节有一个整数值13,我认为这是一个回车符,对吗?
那么为什么 readLine 方法会阻塞呢?服务器通常如何发出信号到达流结束?谢谢。
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;
[...]
}
and I found out that the last byte read has an integer value of 13, which I think it is a carriage return, right?
So why the readLine
method blocks? How does the server usually signal an end of stream is reached? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在网络连接的情况下,当套接字关闭时流将终止。
因此,readLine() 阻塞直到收到“行尾”或您手动关闭连接是完全正常的。当您的
readLine()
收到最后一个值为“13”的字符时,将读取该行并再次开始循环,等待下一行。“最后一行”和其他行没有区别。
为了停止循环,您必须手动关闭某个地方的连接或等待超时。但是,如果没有有关您的通信协议的更多信息,就不可能对此进行更准确的说明。
In the case of a network connection, the stream is terminated when the socket is closed.
So it is perfectly normal that
readLine()
blocks until it received an "end of line" or you close manually the connection. When yourreadLine()
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.
这取决于协议。如果服务器不关闭流,readLine 将阻塞,直到收到正确的行尾。因此,如果服务器从未发送正确的行尾,您就会被阻止。您也许应该使用更多低级方法并尝试获取协议文档,或对其进行逆向工程。
It depends on the protocol. If the server doesn't close the stream, readLine will block until the proper line end is received. So if the server never sends the proper line end, you're blocked. You should maybe use more low-level methods and try to get the protocol documentation, or reverse-engineer it.
确保服务器代码具有 out.println() 而不是 out.print()
make sure that the server code has out.println() instead of out.print()
如果不使用空行,则可以扩展 while 条件:
You can extend the while condition if you do not use empty lines :