js EventSource 长链接
有这么一个场景:服务端处理数据,响应比较慢,为了不让用户体会到网页没有反应,服务端需要把处理的每一步操作返回给前端,前端实时进行打印。
1.ajax 轮询
<script> setInterval("test()",2000); function test() { $.ajax({ url: '/new_window_url/', async:false, type: 'get', success: function (data) { console.log(data) } }) } </script>
2.EventSource 长链接
前端代码:
<!doctype html> <html lang="en"> <head> <title>Sse测试文档</title> <meta charset="utf-8"> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdn.bootcss.com/event-source-polyfill/0.0.9/eventsource.min.js"></script> </head> <body> <div></div> </body> </html> <script> var source = new EventSource('http://127.0.0.1:8080/event/query'); //只要和服务器连接,就会触发open事件 source.addEventListener("open",function(){ console.log("和服务器建立连接"); }); //处理服务器响应报文中的load事件 source.addEventListener("load",function(e){ console.log("服务器发送给客户端的数据为:" + e.data); }); //如果服务器响应报文中没有指明事件,默认触发message事件 source.addEventListener("message",function(e){ console.log("服务器发送给客户端的数据为:" + e.data); }); //发生错误,则会触发error事件 source.addEventListener("error",function(e){ console.log("服务器发送给客户端的数据为:" + e.data); }); </script>
服务端代码:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; @SpringBootApplication @RestController @RequestMapping("event") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @ResponseBody @CrossOrigin @RequestMapping(value="query") public void query(HttpServletResponse response) throws IOException, InterruptedException { response.setHeader("Content-Type","text/event-stream"); response.setContentType("text/event-stream;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("data:Hello World"); out.println("event:load"); out.println("id:140312"); out.println(); out.flush(); out.close(); } }