当前位置:   article > 正文

java Spring MVC 实现 SSE (Server-Sent Event) 服务器发送事件

java使用sse做事件分发

Java:

  1. package com.example.huamao.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import java.util.Random;
  7. /** SSE 服务器发送事件
  8. */
  9. @Controller
  10. public class SSEController {
  11. @RequestMapping(value="/push",produces="text/event-stream;charset=utf-8")
  12. @ResponseBody
  13. public String push() {
  14. Random r = new Random();
  15. try {
  16. Thread.sleep(5000);
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }
  20. return "data:Testing 1,2,3" + r.nextInt() +"\n\n";
  21. }
  22. @RequestMapping(value = "/sseTest", method = RequestMethod.GET)
  23. public String getSSEView () {
  24. return "sseTest";
  25. }
  26. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>sse 测试</title>
  5. </head>
  6. <body>
  7. <div id="msg_from_server"></div>
  8. <script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>
  9. <script type="text/javascript">
  10. if (!!window.EventSource) {
  11. var source = new EventSource('push'); //为http://localhost:8080/testSpringMVC/push
  12. s = '';
  13. source.addEventListener('message', function (e) {
  14. s += e.data + "<br/>"
  15. $("#msg_from_server").html(s);
  16. });
  17. source.addEventListener('open', function (e) {
  18. console.log("连接打开.");
  19. }, false);
  20. source.addEventListener('error', function (e) {
  21. if (e.readyState == EventSource.CLOSED) {
  22. console.log("连接关闭");
  23. } else {
  24. console.log(e.readyState);
  25. }
  26. }, false);
  27. } else {
  28. console.log("没有sse");
  29. }
  30. </script>
  31. </body>
  32. </html>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/335493
推荐阅读
相关标签
  

闽ICP备14008679号