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"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SSE Demotitle>
head>
<body>
    <div id="msgDiv">This is a sse testdiv>
    <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 + "
"
; $("#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

你可能感兴趣的:(Spring,MVC)