4

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

tiger
  • 653
  • 7
  • 18
  • Not exactly a duplicate, but is [a good explanation](http://stackoverflow.com/q/5195452/575527) – Joseph May 07 '13 at 06:38
  • is there a special reason why you used a `while` loop? you're counting from 0 to 10 which is the common purpose of a `for` loop... – Marco Forberg May 07 '13 at 06:40
  • What exactly do you not understand and what do you already understand? What did you try to find out how "it" works? Throwing some code in and saying "please explain" does not seem like a good question for me... – Uooo May 07 '13 at 06:43

1 Answers1

2

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).

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136