我的团队正在用Java从头开始构建一个基本的HTTP服务器,但是一旦用完了请求文本,我们的读者就会阻塞来从套接字的输入流中读取。 我们的情况特有的一些与questions asked previously不匹配的点:
基本代码:
swal({
title: "Sorry but error occurred",
text: "Sorry but error occurred",
type: "error",
allowEscapeKey: true
});
答案 0 :(得分:0)
readLine()
才返回null
,即套接字已被另一方关闭。当readLine()
读取没有先前数据的换行符时,它会返回String
为0的非空length
。因此,您需要相应地修复while
循环:
public void readSocket() {
receivedTime = System.currentTimeMillis();
requestFile = new File("recovery/" + receivedTime + ".txt");
try(
FileWriter fw = new FileWriter(requestFile);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(fw);
)
{
String line;
// read request headers...
do {
line = in.readLine();
if (line == null) return; // socket closed
out.write(line);
out.NewLine();
out.flush();
if (line.isEmpty()) break; // end of headers reached
// process line as needed...
}
while (true);
// check received headers for presence of a message
// body, and read it if needed. Refer to RFC 2616
// Section 4.4 for details...
// process request as needed...
} catch (IOException e) {
e.printStackTrace();
}
}
另见:
While reading from socket how to detect when the client is done sending the request?