this does the trick.
HTML
<!DOCTYPE html>
<html>
<body onload ="registerSSE()" >
<script>
function registerSSE()
{
alert('test 1');
var source = new EventSource('http://frewper:8080/hello/sse');
alert('Test2');
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};
/*source.addEventListener('server-time',function (e){
alert('ea');
},true);*/
}
</script>
<output id ="result"></output>
</body>
</html>
Servlet :
import java.io.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class sse extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
System.out.println("SSE Demo");
response.setContentType("text/event-stream");
PrintWriter pw = response.getWriter();
int i=0;
while(true)
{
i++;
pw.write("event: server-time
"); //take note of the 2
's, also on the next line.
pw.write("data: "+ i + "
");
System.out.println("Data Sent!!!"+i);
if(i>10)
break;
}
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
doPost(request,response);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…