1. 程式人生 > >Spring mvc服務端消息推送(SSE技術)

Spring mvc服務端消息推送(SSE技術)

javascrip tro jstl var 通信 主動 form imp title

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(2000); } 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技術)