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

SSE技術是基於單工通訊模式,只是單純的客戶端向服務端發送請求,服務端不會主動發送給客戶端。服務端採起的策略是抓住這個請求不放,等數據更新的時候才返回給客戶端,當客戶端接收到消息後,再向服務端發送請求,周而復始。javascript

注意:由於EventSource對象是SSE的客戶端,可能會有瀏覽器對其不支持,但谷歌、火狐、360是能夠的,IE不能夠。html

另外WebSocket技術是雙工模式。java

本文使用的是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>

效果如圖所示:jquery

相關文章
相關標籤/搜索