Java、套接字、BufferedReader 和 readline 挂起...... :( [英] Java, sockets, BufferedReader, and readline hang ... :(

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

问题描述

我根本不是 Java 程序员.我实际上会不惜一切代价避免它,但我必须将它用于课堂(在学校意义上).老师要求我们使用Socket()、BufferedReader()、PrintWriter()等各种东西,包括BufferedReader()的readLine()方法.

I'm not a Java programmer at all. I try to avoid it at all costs actually, but it is required that I use it for a class (in the school sense). The teacher requires that we use Socket(), BufferedReader(), PrintWriter() and various other things including BufferedReader()'s readLine() method.

基本上,这就是我遇到的问题.文档明确指出 readLine 应该在输入流的末尾返回 null,但事实并非如此.

Basically, this is the problem I'm having. The documentation clearly states that readLine should return a null at the end of the input stream, but that's not what's happening.

Socket link       = new Socket(this.address, 80);
BufferedReader in = new BufferedReader( new InputStreamReader( link.getInputStream() ));
PrintWriter   out = new PrintWriter(    new PrintWriter(       link.getOutputStream(), true ));

out.print("GET blah blah blah"); // http request by hand
out.flush(); // send the get please

while( (s=in.readLine()) != null ) {

    // prints the html correctly, hooray!!
    System.out.println(s);
}

我没有在 HTML 的末尾结束,而是得到一个空行、一个 0 和另一个空行,然后下一个 in.readLine() 永远挂起.为什么?我的空在哪里?

Instead of finishing at the end of the HTML, I get a blank line, a 0 and another blank line and then the next in.readLine() hangs forever. Why? Where's my null?

我尝试了 out.close() 以查看是否可能是 Yahoo!正在做一个持久的 http会话或其他东西(我认为没有标题就不会我们愿意这样做).

I tried out.close() to see if maybe Yahoo! was doing a persistent http session or something (which I don't think it would without the header that we're willing to do it).

我在网上找到的所有 Java 套接字示例似乎都表明while 循环是正确的形式.我只是不知道足够的 Java 来调试这个.

All the Java sockets examples I'm finding on the net seem to indicate the while loop is the correct form. I just don't know enough Java to debug this.

推荐答案

您的问题是内容编码分块".当响应开始时不知道从 Web 服务器请求的内容的长度时,将使用此选项.它基本上由发送的字节数、CRLF 和字节组成.响应的结束由您看到的确切序列表示.Web 服务器现在正在等待您的下一个请求(这也称为请求流水线").

Your problem is the content encoding "chunked". This is used when the length of the content requested from the web server is not known at the time the response is started. It basically consists of the number of bytes being sent, followed by CRLF, followed by the bytes. The end of a response is signalled by the exact sequence you are seeing. The web server is now waiting for your next request (this is also called "request pipelining").

你有几种可能:

  • 使用 HTTP 1.0 版.这将导致网络服务器在完全发送响应后自动关闭连接.
  • 在发送请求时指定Connection: close"标头.这也将关闭连接.
  • 正确解析分块"的内容编码,并简单地将其视为现在已完成的响应.

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

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