------ 服务器同送技术在我们日常开发中较为常用,早起很多人解决方案是使用Ajax向服务器轮询消息,使浏览器尽可能第一时间获得服务端的消息,这种轮询频率不好控制,会大大增加服务器的压力,该方案基于:当客户端向服务端发送请求,服务端会抓住这个请求不放,等有数据更新的时候才返回给客户端,当客户端接收到消息后,再想服务端发送请求,周而复始。这种方式好处是减少了服务器的请求数量,大大减少了服务器的压力,
##### 基于SSE 演示服务器推送
package com.zili.jit.test;
import java.util.Random;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SseController {
// 使用输出类型为 text/event-stream,这是服务器端SSE的支持,本例演示每5秒向浏览器
// 推送随机消息
@RequestMapping(value="/push",produces="text/event-stream")
public @ResponseBody String push() {
Random r = new Random();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "data:Testing 1,2,3" +r.nextInt() +"\n\n";
}
}
演示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style></style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div id="msgFrompPush"></div>
<script type="text/javascript" >
// EventSource 对象只有新式的浏览器才有(Chrome、Firefox)等,EventSource是SSE的客户端
if(!! window.EventSource){
var source = new EventSource('push');
s='';
source.addEventListener('message',function(e){//添加SSE监听,在这里获得服务器端推送的消息
s +=e.data + "<br/>";
$("#msgFrompPush").html(s);
});
source.addEventListener('open',function(e){
console.log("连接打开");
});
source.addEventListener('error',function(e){
if(e.readyState == EventSource.CLOSED){
console.log("连接关闭");
}else{
console.log(e.readyStete);
}
})
}else {
console.log("你的浏览器不支持 SSE ");
}
</script>
</body>
</html>