• Java Spring使用EventSource进行服务端推送


    Java代码:

            @ResponseBody
            @RequestMapping(value = "/getDate", produces="text/event-stream;charset=UTF-8")
            public void getDate(HttpServletResponse response) throws Exception {
                log.info("getDate event start");
                response.setContentType("text/event-stream");
                response.setCharacterEncoding("UTF-8");
                response.setStatus(200);
                while(!response.getWriter().checkError()){
                    response.getWriter().write("data:"+new Date()+" ");
                    response.getWriter().flush();
                    Thread.sleep(1000);
                }
                response.getWriter().close();
                log.info("getDate event end");
            }

    前端代码(jsp):

        <%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>
         
        <!DOCTYPE html>
        <html>
        <head>
            <title>日期</title>
        </head>
        <body>
        <div id='date'>
        </div>
        <script>
                if (typeof(EventSource) !== "undefined") {
                    var eventSource = new EventSource("/Output/getDate");
                    
                    eventSource.onmessage = function (event) {
                        document.getElementById("date").innerHTML = event.data;
                             
                    }            
                    eventSource.addEventListener('error', function (event) {
                        console.log("错误:" + event);
                    });
                    eventSource.addEventListener('open', function (event) {
                        console.log("建立连接:" + event);
                    });
                }
                else {
                    document.getElementById("date").innerHTML = "抱歉,您的浏览器不支持 server-sent 事件 ...";
                }   
            
        </script>
         
        </body>
        </html>



  • 相关阅读:
    仿照everything写的一个超级速查 原创
    [转]SharePoint 2013 Online App Development – Part 1
    [转]SharePoint 2013 App 开发 (2)
    [转]ASP.NET自定义控件复杂属性声明持久性浅析
    HasRights方法参数
    故障分析神器——BTrace
    JVM——Memory Analyzor分析内存溢出
    关于句柄
    Java内存区域与内存溢出
    命令行的使用
  • 原文地址:https://www.cnblogs.com/tiancai/p/14791137.html
Copyright © 2020-2023  润新知