HTML5服务器消息推送(java版)

时间:2021-01-24 10:16:57

前端代码(html5.html):

<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head><title>消息推送</title>
<script type="text/javascript">
var source = new EventSource("fail.jsp");
source.onmessage=function(event)
  {
  document.getElementById("result").innerHTML += event.data + "<br />";
  };
source.onerror = function(event){
alert("onerror");
};
source.onopen = function(event){
alert("onopen");
};
</script>
</head>
<body>
  <div id="result">123</div>
</body>
</html>

后台代码(fail.jsp):

<% 
response.setHeader("Content-Type","text/event-stream");
response.setHeader("Cache-Control","no-cache");
out.println("data: "+new java.util.Date(System.currentTimeMillis()).toString());
out.println(); out.flush();
%>

注意:后台代码解释:

(1)把报头"Content-Type"设置为"text/event-stream"

(2)规定页面不能缓存

(3)输出发送的数据始终以:"data: "开头(数据一定要以两个换行符为结束)

(4)向客户刷出数据