java 防止HttpServletResponse输出流在get/post/service之后关闭(Polarion)

dy2hfwbg  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(127)

我正在为Polarion ALM开发一个HttpServlet(javax.servlet.http.HttpServlet),我希望保持到客户机的连接/输出流打开,即使在服务方法结束后,也要定期对其进行ping。

public class CustomServlet extends HttpServlet {
[...]
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        [...]
        response.setStatus(200);
        response.setContentType("application/x-ndjson");
        ExperimentalPingThread thread = new ExperimentalPingThread();
        thread.setOut(response.getOutputStream())
        Thread t = new Thread(thread);
        t.start();
        return;
        }
[...]
}
public class ExperimentalPingThread implements Runnable {

    ServletOutputStream out;

    @Override
    public void run() {
        JSONObject configJson = new JSONObject();
        configJson.put("type", "ping");
        configJson.put("payload", new JSONObject());
        String outString = configJson.toString() + "\n";

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                System.out.println("sending Ping: " + outString);
                try {                   
                    out.write(outString.getBytes());
                    out.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        timer.schedule( task, 0L ,1000L);
    }

    public void setOut(ServletOutputStream out) {
        this.out = out;
    }
}

我知道ExperimentalPingThread类有点多余,因为Timer类本身也在创建一个新的线程,但正如您从该类名称中看到的,这当前处于"实验"状态。
客户端(访问Polarion LiveReportPage的浏览器)似乎未收到写入输出流的定期ping。在调查前端后,似乎在服务方法"结束"后立即关闭了OutputStream,因此ping从未到达客户端。
是否有一些HttpServlet生命周期可以强制关闭,我是否能够操纵它?

2ic8powd

2ic8powd1#

服务方法完成后,Servlet输出流将关闭。
您可以在这里找到有关HttpServlet生命周期的更多详细信息:What is the lifecycle of a HttpServlet?

相关问题