如何在Java套接字中识别EOF? [英] How do I recognize EOF in Java Sockets?
本文介绍了如何在Java套接字中识别EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想识别Java套接字中的数据流结束。当我运行下面的代码时,它只是卡住并继续运行(它停留在值 10
)。
I want to recognize end of data stream in Java Sockets. When I run the code below, it just stuck and keeps running (it stucks at value 10
).
我也希望程序下载二进制文件,但最后一个字节总是不同的,所以我不知道如何在 >(实用)。
I also want the program to download binary files, but the last byte is always distinct, so I don't know how to stop the while (pragmatically).
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();
感谢任何提示。
推荐答案
- 您应该使用现有的HTTP库。请参见此处。
- 您的代码按预期工作。服务器不会关闭连接,
dataBuffer
永远不会变为-1
。这是因为默认情况下连接在HTTP 1.1中保持活动状态。使用HTTP 1.0,或在请求中输入连接:关闭
标题。
- You should use existing libraries for HTTP. See here.
- Your code works as expected. The server doesn't close the connection, and
dataBuffer
never becomes-1
. This happens because connections are kept alive in HTTP 1.1 by default. Use HTTP 1.0, or putConnection: close
header in your request.
例如:
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();
这篇关于如何在Java套接字中识别EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文