赞
踩
Server Send Event 是服务器主动向客户端推送消息的一种技术。消息类型为“text/event-stream”。
chrome edge浏览器支持。
注意produces是“text/event-stream”,方法是"/push”,客户端EventSoure在new时需要和方法名称一致,即监听的此方法,每个客户端最多可以有6个event-stream链接,服务器端返回的数据前必须加“data:”。
- package com.hj.ServerSendEvent;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import java.util.Random;
-
- /**
- * describe
- *
- * @author huangjuan
- * @date 2023/2/15 9:59
- */
- @Controller
- public class ServerSentEventController {
- @RequestMapping(value = "/push",produces = "text/event-stream")
- @ResponseBody
- public String pushToBrowser() {
- Random random = new Random();
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- return "data: server send event push message test:" + random.nextInt() + "\n\n";
- }
- }
- <!DOCTYPE html>
- <head>
- <meta charset="UTF-8">
- <title>测试</title>
- </head>
- <body>
- <div>服务器端推送测试</div>
- <div id="serverSendEventDiv"></div>
- </body>
- <script type="text/javascript">
- if(window.EventSource) {
- const source = new EventSource("push");
- let s = '';
- // 监听打开连接
- source.addEventListener('open', function (e) {
- console.log("连接打开")
- }, false);
- source.addEventListener('message', function (e) {
- s += e.data + '<br/>';
- document.getElementById("serverSendEventDiv").innerHTML = s;
- })
- // 监听关闭连接
- source.addEventListener('close', function (e) {
- if (e.readyState === EventSource.CLOSED) {
- console.log("连接关闭")
- } else {
- console.log(e.readyState)
- }
- }, false);
- source.addEventListener("error", function(err) {
- console.log(JSON.stringify(err))
- console.log(err)
- // 类似的返回信息验证,这里是实例
- err && err.status === 401 && console.log('not authorized')
- })
- } else {
- alert("你的浏览器不支持sse")
- }
- </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。