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