Question

I am using a servlet as my server to send updates to my jsp client(Using HTML5 SSE). This is my jsp code

<script type="text/javascript">

    if(typeof(EventSource)!=="undefined")
      {
      var source=new EventSource("server");
      source.onmessage=function(event)
        {
        document.getElementById("news1").innerHTML+=event.data + "<br />";
        };
      }
    else
      {
      document.getElementById("news1").innerHTML="Sorry, your browser does not support server-sent events...";
      }
      </script>

This is my servlet doGet method.

response.setContentType("text/event-stream");  

        PrintWriter out = response.getWriter();  

        int messagesSent = 0;  

            out.print("data: {" + messagesSent++ + "}\n\n");  
            out.flush();  
            out.close();

This is working fine and server is sending updates approximately in every 3 seconds by default. I want to change this to every 10 minutes. Is it possible? If yes,How?

Was it helpful?

Solution

In your response you need to send retry: with the timeout in milliseconds

Therefore you doGet should look like this....

response.setContentType("text/event-stream");   

PrintWriter out = response.getWriter();  

int messagesSent = 0;  

out.print("retry: 600000\n"); //set the timeout to 10 mins in milliseconds
out.print("data: {" + messagesSent++ + "}\n\n");  
out.flush();  
out.close();

See HTML5Rocks.com for more info an the EventSource object.

OTHER TIPS

The above solution does not work with Chrome because of the ContentType.

Chrome expects this:

response.setContentType("text/event-stream;charset=UTF-8");

Find a sample googling "milestonenext HTML5 Server-Sent Events Sample with Java Servlet as Event Server"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top