1. 程式人生 > >springMVC學習--8 SSE(Server Send Event)--服務端推送技術之一

springMVC學習--8 SSE(Server Send Event)--服務端推送技術之一

SSE技術,即Server Send Event與非同步Servlet 3.0+、Websocket等為伺服器端推送技術。SSE技術的特點是使用Http協議,輕量級易使用,在伺服器端只要通過ContentType=“text/event-stream; charset=UTF-8”標明支援SSE即可,客戶端也只需要建立請求到伺服器端url的EventSource,再在EventSource上註冊EventListener。相比之下,WebSocket採用的TCP/IP協議,設定較為複雜。

SSE示例:

1. 伺服器端的Controller

package com.controller;

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 { /** * "text/event-stream; charset=UTF-8"表明支援SSE這一伺服器端推送技術, * 欄位後面部分"charset=UTF-8"必不可少,否則無法支援SSE。 * 伺服器端傳送的資料是連續的Stream,而不是一個數據包, * 因此瀏覽器接收到資料後,不會關閉連線。 * * @return
服務端向瀏覽器推送的訊息,具有一定的格式要求,詳見SSE說明 */
@RequestMapping(value = "/push", produces = "text/event-stream; charset=UTF-8") public @ResponseBody String push() { Random random = new Random(); try { Thread.sleep(5000); } catch (InterruptedException ex) { ex.printStackTrace(); } return
"data:This is a test data " + random.nextInt() + "\n\n"; // SSE 要求的資料格式,詳見SSE說明 } }

2. 瀏覽器端(jsp)用EventSource作為客戶端

<%@ 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="msgDiv">This is a sse test</div>
    <script type="text/javascript" src="assets/js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        if (!!window.EventSource) {
            var source = new EventSource('push');
            console.log(source.readyState);
            s = ' ';

            /* message event listener */
            source.addEventListener('message', function(e) {
                s += e.data + "<br/>";
                $("#msgDiv").html(s);
            });

            /* open event listener */
            source.addEventListener('open', function(e) {
                console.log("Connection is open");
            }, false);

            /* error event listener */
            source.addEventListener('error', function(e) {
                if (e.readyState == EventSource.CLOSED) {
                    console.log("Connection is closed");
                } else {
                    console.log("e.readyState");
                }
            }, false);
        } else {
            console.log("Your web browser dosen't support EventSource.");
        }
    </script>
</body>
</html>

3. 測試結果

瀏覽器顯示:
This is a test data -79652348
This is a test data -1095646155
This is a test data -1057602112
This is a test data -136222957
This is a test data 1348517168