tiger
tiger

Reputation: 653

Server sent events using server side as servlets

I have a running implementation of simple server sent events using servlets.

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
    // TODO Auto-generated method stub

    try
    {
        System.out.println("Server Sent Events");
        response.setContentType("text/event-stream");

        PrintWriter pw = response.getWriter();
        int i=0;
        pw.write("retry: 30000\n"); 
        System.out.println("----------------------");
        while(true)
        {
            i++;

            pw.write("data: "+ i + "\n\n");
            System.out.println("Data Sent : "+i);
            if(i>10)
                break;
        }

    }catch(Exception e){
        e.printStackTrace();
    }
}

And my client side code is

<!DOCTYPE html>
<html>
<body onload ="SSE()" >
<script>

    function SSE()
    {
        var source = new EventSource('GetDate');  
        source.onmessage=function(event)
        {
            document.getElementById("result").innerHTML+=event.data + "<br />";
        };
    }
</script>
<output id ="result"></output>

</body>
</html>

But can anyone explain me how this actually works? As in how does the server send the chunk of 11 integers in one go? And is it necessary to flush or close the Printwriter here. Does the server every time makes a new connection to send the data

Upvotes: 4

Views: 2710

Answers (1)

Juned Ahsan
Juned Ahsan

Reputation: 68715

Response stream writes the content on the message body of http packet. As you are looping the integers so, all of them are getting added to the content one after the other. Unless flush/close is not closed on the stream you can keep writing on the stream and everything will by sent at once when you send the response.

Also some note about flush and close.You don't need to slufh,the servletcontainer will flush and close it for you. The close by the way already implicitly calls flush.Calling flush is usually only beneficial when you have multiple writers on the same stream and you want to switch of the writer (e.g. file with mixed binary/character data), or when you want to keep the stream pointer open for an uncertain time (e.g. a logfile).

Upvotes: 2

Related Questions