3

I am developing a HttpServlet (javax.servlet.http.HttpServlet) for Polarion ALM and I want to keep the connection/outputstream to a client open with a periodic ping written on it even after the service method has concluded.

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;
    }
}

I am aware that the ExperimentalPingThread class is kinda redundant because the Timer class itself is creating a new Thread aswell but as you can see from this class name, this is currently in an "experimental" state.

The client (Browser accessing a Polarion LiveReportPage) seems to not receive the periodic ping written into the outputstream. After investigating the frontend side it seems that the OutputStream has been closed right after the service methode has "concluded" so the ping never reaches the client.

Is there some HttpServlet LifeCycle that forces a close and am I able to manipulate this?

cfhenk
  • 31
  • 2

1 Answers1

1

Servlet output stream will be closed after the service method is finished.

You can find more details about HttpServlet's life cycle here: What is the lifecycle of a HttpServlet?

tinsukE
  • 930
  • 9
  • 20
  • Do you know if it's possible to use a proxy endpoint for this? Client sends request to servlet => servlet proxies the request to another server and this server streams the response back to the client – baitendbidz Jan 13 '23 at 15:02