我正在编写一个http服务器,但在从套接字中读取时遇到了问题。我的问题是来自客户端的inputStream
永远不会结束,并且它会一直读取直到客户端关闭。我知道客户端在发送http请求后不会立即关闭与服务器的连接。当客户端发送完所有请求数据(即头部+正文)时,如何退出while循环
。
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并且客户端没有关闭连接,仍然会卡住。
GET
请求,你可以在获取到\r\n\r\n
后停止;如果有请求体,则在从请求体中读取了Content-Length
字节后停止。 - EsailijaDataInputStream
来完成这个任务。是的,我知道它的readLine()
方法已经被弃用了。 - user207421