Spring mvc服务端消息推送(SSE技术)

时间:2023-03-10 06:56:23
Spring mvc服务端消息推送(SSE技术)

SSE技术是基于单工通信模式,只是单纯的客户端向服务端发送请求,服务端不会主动发送给客户端。服务端采取的策略是抓住这个请求不放,等数据更新的时候才返回给客户端,当客户端接收到消息后,再向服务端发送请求,周而复始。

注意:因为EventSource对象是SSE的客户端,可能会有浏览器对其不支持,但谷歌、火狐、360是可以的,IE不可以。

另外WebSocket技术是双工模式。

本文使用的是Spring4.x,无需其他类库,服务端代码如下:
package com.wzy.spring; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "sse";
} @RequestMapping(value="push",produces="text/event-stream")
public @ResponseBody String push(){
System.out.println("push msg..");
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
} //注意:返回数据的格式要严格按照这样写,‘\n\n’不可少
return "data:current time: "+new SimpleDateFormat("YYYY-MM-dd hh:mm:ss").format(new Date())+"\n\n";
}
}
客户端代码如下,sse.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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方式消息推送</title>
</head>
<body> <div id="msgFromPush"></div>

  <!--这里的jquery仅仅用于数据的展示,不影响消息推送-->
<script type="text/javascript" src="<c:url value='resources/jquery-1.10.2.js'/>"></script>
<script type="text/javascript">
if(!!window.EventSource){
var source = new EventSource('push');
s = '';
source.addEventListener('message',function(e){
console.log("get message"+e.data);
s+=e.data+"<br/>";
$("#msgFromPush").html(s);
}); source.addEventListener('open',function(e){
console.log("connect is open");
},false); source.addEventListener('error',function(e){
if(e.readyState == EventSource.CLOSE){
console.log("connect is close");
}else{
console.log(e.readyState);
}
},false);
}else{
console.log("web is not support"); } </script>
</body>
</html>

效果如图所示:

Spring mvc服务端消息推送(SSE技术)