SSE服务端主动推送只有一个请求拒绝轮训

网上看了很多sse(Server Sent Events) 推送的案例 但是基本上都违背了sse的功能,
sse应该是建立在http请求的时候告诉浏览器数据还没有写完,http请求还没有结束,然后通过输出流的方式一直写出数据。下面开始实践

if(typeof(EventSource)!=="undefined") {
        //判断是否支持EventSource
      var source = new EventSource('push'); //为http://localhost:8080/sse/push
      source.addEventListener('message', function (e) {
     
      }
      source.addEventListener('open', function (e) {
     
      }
      source.addEventListener('error', function (e) {
     
      }
}

java代码

 @RequestMapping(value = "/push")
    @ResponseBody
    public String getStreamDataImprove(HttpServletResponse httpServletResponse) {
     
        httpServletResponse.setContentType("text/event-stream");
        httpServletResponse.setCharacterEncoding("utf-8");
        String s = "data:test 开始冲啊 喵喵喵 ------- "+new Date() +"\n\n";
        while (true) {
     
            try {
     
                PrintWriter pw=httpServletResponse.getWriter();
                Thread.sleep(1000L);
                pw.write(s);
                pw.flush();
            } catch (IOException | InterruptedException e) {
     
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(java,http,websocket,restful)