赞
踩
当客户端向服务端发送请求,服务端抓住该请求不放,等有数据更新时才返回给客户端,当客户端接收到消息后,再向服务端发送请求。
好处:减少服务端的请求数量,大大减小服务器的压力
1.控制器
package com.wen.springmvc4.web;
import java.util.Random;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SseController {
//服务器端SSE支持输出媒体类型为text/event-stream
@RequestMapping(value="/push",produces="text/event-stream")
public @ResponseBody String push(){
Random r=new Random();
try{
Thread.sleep(5000); //睡眠5秒
}catch (InterruptedException e) {
e.printStackTrace();
}
return "data:Test"+r.nextInt()+"\n\n";
}
}

2.页面
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SSE Demo</title>
</head>
<body>
<div id="msgFrompPush"></div>
<script type="text/javascript" src="<c:url value="assets/js/jquery.js"></c:url>"></script>
<script type="text/javascript">
//EventSource对象只有新式浏览器才有(Chrome、Firefox),EventSource是SSE的客户端
if(!!window.EventSource){
var source=new EventSource('push');
s='';
//添加SSE客户端监听,在此获得服务器端推送的消息
source.addEventListener('message',function(e){
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.readyState);
}
},false);
}else{
console.log("浏览器不支持")
}
</script>
</body>
</html>

3.MyMvcConfig配置
添加转向sse.jsp页面的映射
/**页面转向 ,简化代码量**/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/toUpload").setViewName("/upload");
registry.addViewController("/sse").setViewName("/sse");
}
/**页面转向 **/
将程序部署到Tomcat,运行,访问http://localhost:8080/SpringMVC/sse
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。