当前位置: 首页 > article >正文

Java SSE流式数据前后端实现

#Java SSE流式数据前后端实现

Java后端实现

@RestController
public class SSEController {

   @GetMapping(value = "/sse/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
   public SseEmitter streamSse() throws InterruptedException, IOException {
       SseEmitter emitter = new SseEmitter(60_000L);
       new Thread(() -> {  // 异步通信,否则消息会全部完成后发送
           try {
               for (int i = 1; i <= 5; i++) {
                    Thread.sleep(1000); // 模拟延迟
                    emitter.send("data: Message " + i + "\n\n");
               }
               emitter.complete();
           } catch (Exception e) {
               emitter.completeWithError(e);
           }
       }).start();
       return emitter;
   }
}

##前端代码实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example</title>
</head>
<body>
    <div id="output"></div>
    <script>
        const output = document.getElementById('output');
      const eventSource = new EventSource('http://localhost:8080/sse/stream');
        eventSource.onmessage = function(event) {
		console.log(event);
            const data = event.data; 
            const newElement = document.createElement('div');
            newElement.textContent = data;
            output.appendChild(newElement);
        };
        eventSource.onerror = function(e) {
            console.error('SSE Connection Error:', e);
            eventSource.close();
            const newElement = document.createElement('div');
            newElement.textContent = "Connection Closed";
            output.appendChild(newElement);
        };
    </script>
</body>
</html>

http://www.kler.cn/a/564211.html

相关文章:

  • 第2_3章_入门管理资源服务器
  • 定义数组存储3部汽车对象(class1)
  • 2025系统架构师(一考就过):案例之四:架构复用、架构评估、特定架构(DSSA)、架构开发方法(ABSD)
  • 如何利用爬虫测试1688商品详情接口
  • Python数据分析篇:(二)数组索引、切片和运算
  • 【12】智能合约开发入门
  • 基于STM32的智能家居能源管理系统
  • AI大模型-提示工程学习笔记19-自我反思
  • RISCV指令集解析
  • 大模型应用:多轮对话(prompt工程)
  • 高防IP能够给网站带来哪些好处?
  • 软件工程复试专业课-UML
  • DeepSeek 发布 FlashMLA:突破H800性能极限,重塑边缘计算格局
  • 过滤器 二、过滤器详解
  • CogFindCircleTool工具
  • Python 的历史进程
  • 自动化设备对接MES系统找DeepSeek问方案
  • 【git】【reset全解】Git 回到上次提交并处理提交内容的不同方式
  • PageHelper新发现
  • React低代码项目:问卷编辑器