套接字:BufferedReader readLine() 块

发布于 2024-11-10 07:56:53 字数 430 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

久夏青 2024-11-17 07:56:53

在网络连接的情况下,当套接字关闭时流将终止。

因此,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 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.

与酒说心事 2024-11-17 07:56:53

这取决于协议。如果服务器不关闭流,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.

审判长 2024-11-17 07:56:53

确保服务器代码具有 out.println() 而不是 out.print()

make sure that the server code has out.println() instead of out.print()

清风不识月 2024-11-17 07:56:53

如果不使用空行,则可以扩展 while 条件:

while((line = br.readLine())!=null && line.length() > 0) {
   // ...
}

You can extend the while condition if you do not use empty lines :

while((line = br.readLine())!=null && line.length() > 0) {
   // ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文