基于SSE(服务器端发送事件)的服务器端推送。(类似于ajax轮询)
当我们需要使用server向浏览器主动推送数据的时候,请考虑使用该项技术,而不是考虑具有双向通讯功能的websocket;
代码实现
jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>管理员登录</title>
</head>
<body>
<div id="msgFromServerPush"></div>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
;$(function () {
if(!!window.EventSource){
console.log("support……");
var source=new EventSource('/admin/push/'+new Date().getMilliseconds());
s = '';
source.addEventListener('message', function(e) {
s += e.data + "<br/>";
$("#msgFromServerPush").html(s);
});//添加客户端的监听
source.addEventListener('open', function(e) {
console.log("连接打开");
}, false);
source.addEventListener('error',function(e){
if(e.readyState==EventSource.CLOSED){
console.log("连接关闭");
}else{
console.log(e.readyState);
}
});
}else {
console.log("not support……");
}
});
</script>
</body>
</html>
控制器:
@RequestMapping(value = "push/{id}",produces = "text/event-stream")
@ResponseBody
public String push(@PathVariable String id){
System.out.println("id"+id);
Random r=new Random();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "data:server push data "+id+"-------------"+r.nextInt()+"\n\n";
}
注意:return data: 这个是固定的。
这样服务器会同时互不干扰的向两个窗口推送数据