【发布时间】:2012-01-19 00:25:08
【问题描述】:
我用 Java 为 HTTP 消息编写了一个标记器。它有一个方法nextToken(),它应该返回一个包含接收到的整个HTTP 消息的字符串。问题是消息在预期的正文大小被读取之前就结束了。
我将输入流一直读取到正文的开头。然后我尝试从流中读取 n 个字节,其中 n 是 Content-Length 标头中规定的主体的字节大小。问题是在while 循环内,charsRead = in.read(buffer) 行阻塞,因为输入流中没有更多的输入。但它发生在 n 个字节被读取之前。
示例:在大小为 12,493 的主体中,当预期读取更多 675 个字节时,它会阻塞。
输入流使用 UTF-8,因此每个字节都被编码为一个 char。
/* Somewhere else in the code:
InputStreamReader _isr =
new InputStreamReader(clientSocket.getInputStream(), "UTF-8")
*/
BufferedReader in = new BufferedReader(_isr);
StringBuilder tmp = new StringBuilder();
String line = "";
boolean body = false;
int bodylen = -1;
for (;;) {
line = in.readLine();
if (line == null)
break;
if (line.equals("")) { /* We've reached the body */
body = true;
break;
}
tmp.append(line + "\r\n");
if ((bodylen == -1) && (line.contains("Content-Length:"))) {
/* Make `bodylen` hold the length of the body */
String[] splitted = line.split("Content-Length:");
bodylen = Integer.parseInt(splitted[1].trim());
}
}
if (body == true) {
int charsRead;
char[] buffer = new char[1024];
while (bodylen > 0) {
charsRead = in.read(buffer);
if (charsRead == -1)
break;
bodylen -= charsRead;
tmp.append(buffer);
}
}
为什么会发生以及如何解决?
【问题讨论】: