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

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>

相关文章:

  • Plugin ‘mysql_native_password‘ is not loaded`
  • vue3中ref和reactive响应式数据、ref模板引用(组合式和选项式区别)、组件ref的使用
  • Vue 3 响应式系统深度探索:构建购物车应用 - 精通 `watch` 和 `computed` 的响应式数据
  • 【大语言模型,数据向量化】向量化时使用本地HuggingFaceEmbeddings失败,调用embeddings时仍会去Huggingface下载的解决方法
  • 拉链表介绍
  • PySide(PyQT)重新定义contextMenuEvent()实现鼠标右键弹出菜单
  • SpringSecurity基于JWT实现Token的处理
  • 老旧android项目编译指南(持续更)
  • 【Java项目】基于Spring Boot的闲一品交易系统
  • Pytorch实现之使用生成对抗神经网络平衡数据
  • 树莓百度百科更新!宜宾园区业务再添新篇
  • HarmonyOS 项目集成腾讯云即时通信 IM SDK
  • 2025年02月27日Github流行趋势
  • JavaWeb基础专项复习7——JSON
  • Spring Boot操作MaxComputer(保姆级教程)
  • 一文掌握模拟登录的基本原理和实战
  • mySQL复习
  • 系统架构设计师考点——嵌入式技术
  • c# winfrom增加进度条
  • Redis Stream基本使用及应用场景
  • 免费做四年级题的网站/百度关键词挖掘查询工具
  • 网站导航固定/电商营销策划方案范文
  • 网站绿标怎么做/舟山百度seo
  • wordpress 30分钟过期/深圳网站营销seo费用
  • 网站建设公司考察/网站备案查询系统
  • 学校网站做几级等保/昆明百度推广优化