Skip to content

SSE (Server-Sent Events) 服务器发送事件

SSE协议本质上就是一个Http的get请求,当然也是支持Https,服务端在接到该请求后,返回状态。同时请求头设置也变为流形式。

shell
 Content-Type: text/event-stream,
 Cache-Control: no-cache,
 Connection: keep-alive

前端实现

通过 EventSource 创建一个 EventSource 对象,然后通过 onmessage 事件监听服务器发送的消息。

js
const sse = () => {
  const eventSource = new EventSource('http://localhost:9000/service-uni-app/sse');
  eventSource.onmessage = function (event) {
    console.log(event.data);
    sseRes.value = event.data;
  };
};

后端接口实现

通过持续发送消息给客户端

shell
    /**
     * 模拟SSE serve send event
     * */
    @GetMapping(value = "/sse")
    public String sse(HttpServletResponse response) {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");
        String s = "";
        while (true) {
            s = "data: " + new Date() + "\n\n";
            try {
                PrintWriter pw = response.getWriter();
                Thread.sleep(1000);
                pw.write(s);
                pw.flush();
            } catch (Exception e) {

            }
        }
    }

By Modify.