use*_*912 1 java sockets http eof
我想识别Java套接字中的数据流结束.当我运行下面的代码时,它只是卡住并继续运行(它停留在值10).
我也希望程序下载二进制文件,但最后一个字节总是不同的,所以我不知道如何停止while(实用).
String host = "example.com";
String path = "/";
Socket connection = new Socket(host, 80);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.write("GET "+ path +" HTTP/1.1\r\nHost: "+ host +"\r\n\r\n");
out.flush();
int dataBuffer;
while ((dataBuffer = connection.getInputStream().read()) != -1)
System.out.println(dataBuffer);
out.close();
Run Code Online (Sandbox Code Playgroud)
谢谢你的任何提示.
dataBuffer永远不会成为连接-1.这是因为默认情况下连接在HTTP 1.1中保持活动状态.使用HTTP 1.0,或Connection: close在请求中添加标头.例如:
out.write("GET "+ path +" HTTP/1.1\r\nHost: "+ host +"\r\nConnection: close\r\n\r\n");
out.flush();
int dataBuffer;
while ((dataBuffer = connection.getInputStream().read()) != -1)
System.out.print((char)dataBuffer);
out.close();
Run Code Online (Sandbox Code Playgroud)
实际上你的代码不正确.
在HTTP 1.0中,每个连接都被关闭,因此客户端可以检测输入何时结束.
在具有持久连接的HTTP 1.1中,底层TCP连接保持打开状态,因此客户端可以检测输入何时以以下两种方式之一结束:
1)HTTP Server放置一个Content-Length标题,指示响应的大小.客户端可以使用它来了解何时完全读取响应.
2)发送响应Chunked-Encoding意味着它以前缀为每个块大小的块的形式出现.使用此信息的客户端可以从服务器接收的块构建响应.
您应该使用HTTP客户端库,因为实现通用HTTP客户端并非易事(我可能会说).
要在您发布的代码中具体说明,您应该遵循上述方法之一.
此外,您应该读取行,因为HTTP是行终止协议.
就像这样:
BufferedReader in =new BufferedReader(new InputStreamReader( Connection.getInputStream() ) );
String s=null;
while ( (s=in.readLine()) != null) {
//Read HTTP header
if (s.isEmpty()) break;//No more headers
}
}
Run Code Online (Sandbox Code Playgroud)
通过发送Connection: closekhachik的建议,完成工作(因为关闭连接有助于检测输入结束)但性能变差,因为每个请求都会启动一个新连接.
当然这取决于你想做什么(如果你关心与否)
| 归档时间: |
|
| 查看次数: |
8583 次 |
| 最近记录: |