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

查看:129
本文介绍了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.

推荐答案

你的问题是内容编码chunked 。当在响应开始时不知道从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。这将导致Web服务器在完全发送响应后自动关闭连接。

  • 发送请求时指定Connection:close标头。这也将关闭连接。

  • 正确解析内容编码chunked并简单地将其视为响应现在已完成 - 它是什么。

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

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