这就行了。
断续器
<!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>
服务 :
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\n\n"); //take note of the 2 \n 's, also on the next line.
pw.write("data: "+ i + "\n\n");
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);
}
}