赞
踩
- package test;
- import java.util.Random;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- @Controller
- @RequestMapping(value = "/test")
- public class SEEController {
- //设置响应格式
- @RequestMapping(value = "/push", produces = "text/event-stream;charset=UTF-8")
- public @ResponseBody String push() {
- Random r = new Random();
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //SSE返回数据格式是固定的以data:开头,以\n\n结束
- return "data:Testing 1,2,3" + r.nextInt() + "\n\n";
- }
- }
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>SSE Demo</title>
- </head>
- <body>
- <div id="msg_from_server">12222</div>
- <script type="text/javascript" src="../js/jquery.js"></script>
- <script type="text/javascript">
- if (!!window.EventSource) {
- var source = new EventSource('/test/test/push'); //为http://localhost:8080/testSpringMVC/push
- s = '';
- source.addEventListener('message', function(e) {
- s += e.data + "<br/>"
- $("#msg_from_server").html(s);
- });
- source.addEventListener('open', function(e) {
- console.log("连接打开.");
- }, false);
- source.addEventListener('error', function(e) {
- if (e.readyState == EventSource.CLOSED) {
- console.log("连接关闭");
- } else {
- console.log(e.readyState);
- }
- }, false);
- } else {
- alert(4);
- console.log("没有sse");
- }
- </script>
- </body>
- </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。