我现在正在编写一个 http 服务器,但从套接字读取时遇到问题。我的问题是inputStream
来自客户端的消息永远不会结束,它会一直读取直到客户端关闭。我知道客户端在发送 http 请求后并没有立即关闭与服务器的连接。while loop
当客户端发送所有请求数据(即标头+正文)时, 如何退出。
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("")){ // last line of request header is blank
break; // quit while loop when last line of header is reached
} else {
request = request + line + "\n";
}
}
在阅读了你们的评论和回答后,这就是我想出的,
is = incoming.getInputStream();
os = incoming.getOutputStream();
in = new Scanner(is);
out = new DataOutputStream(os);
RequestHandler rh = new RequestHandler();
int length = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("")) { // last line of request message
// header is a
// blank line
break; // quit while loop when last line of header is
// reached
}
if (line.startsWith("Content-Length: ")) { // get the
// content-length
int index = line.indexOf(':') + 1;
String len = line.substring(index).trim();
length = Integer.parseInt(len);
}
request = request + line + "\n";
}
byte[] body = new byte[length];
int i = 0;
while (i < length) {
byte b = in.nextByte();
body[i] = b;
i++;
}
但是,我仍然不明白按字节读取。我可以编写我的代码来读取直到-1,但是当没有 EOF 并且客户端没有关闭连接时仍然卡住。