//servlet program for sse
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class server
*/
public class server extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost()..method called.....");
// Besides "text/event-stream;", Chrome also needs charset, otherwise
// does not work
// "text/event-stream;charset=UTF-8"
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
PrintWriter out = response.getWriter();
while (true) {
System.out.println("doPost()..method called.....");
out.print("id: " + "ServerTime" + "\n");
out.print("data: " + new Date().toLocaleString() + "\n\n");
out.flush();
// out.close(); //Do not close the writer!
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
--------------------------------------------------------------------------------------------------------------------------
//html code.....
<html>
<head>
<title>sky</title>
<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>
</head>
<body>
<div id="news1"></div>
</body>
</html>