Java,HTTP和&套接字:何时停止读取请求但保持套接字打开?

时间:2017-04-28 18:35:29

标签: java sockets http

我的团队正在用Java从头开始构建一个基本的HTTP服务器,但是一旦用完了请求文本,我们的读者就会阻塞来从套接字的输入流中读取。 我们的情况特有的一些与questions asked previously不匹配的点:

  • 我们希望在处理请求时保持套接字打开并生成回送
  • 的响应
  • 我们首先不解析数据,而是首先将它从套接字中读出并将整个内容放入恢复文件中。然后我们开始从文件中解析和验证,以确保在发生灾难时我们不会丢失请求。

基本代码:

swal({
  title: "Sorry but error occurred",
  text: "Sorry but error occurred",
  type: "error",
  allowEscapeKey: true
});

1 个答案:

答案 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?

相关问题