vendredi 15 mai 2015

Streaming output java

I have a servlet, mapped to an URL, which does a long task and outputs some data while it's working.

What I want to do is to call this url and see output in real-time.

Let's take this as an example:

package com.tasks;

public class LongTaskWithOutput extends HttpServlet {
    private static final long serialVersionUID = 2945022862538743411L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.addHeader("Content-Type", "text/plain");
        PrintStream out = new PrintStream(response.getOutputStream(), true);

        for(int i=0; i<10;i++) {
            out.println("# " + i);
            out.flush();
            try {
                Thread.sleep(1000);
            } catch(Exception e){}
        }
    }

}

With the following in web.xml:

...
<servlet>
    <servlet-name>LongTaskServlet</servlet-name>
    <servlet-class>com.tasks.LongTaskWithOutput</servlet-class>
    <description>Long Task Servlet</description>
</servlet>
<servlet-mapping>
    <servlet-name>LongTaskServlet</servlet-name>
    <url-pattern>/longTask</url-pattern>
</servlet-mapping>
...

What happens

If I browse localhost/myApp/longTask, the browser makes me wait 10 seconds, then prints out all text at once.

What should happen

The text should be sent to the browser as soon as it's written to the output stream, and the browser should render one line every second.

As you can see, I already put an out.flush() to be sure that the stream flushes every second, but it still doesn't work.

I also tried with response.flushBuffer(), but I had the same result.

Is there a way to achieve this?

Aucun commentaire:

Enregistrer un commentaire