EventSource 对象用于接收服务器发送事件通知,是网页自动获取来自服务器的更新

时间:2021-02-19 13:15:47

//--------------------------------客户端代码-----------------------------

if(typeof(EventSource) !== "undefined") {
 var source = new EventSource("../api/v1/event.source");
 source.onmessage = function(event) {
   $("#content_event").html(event.data + "<br>");
 };

else {
  $("#content_event").html("你的浏览器不支持 server-sent事件");
}

//--------------------------------服务端代码-----------------------------
@RequestMapping(value = "/event.source",method = {RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public String eventSource(HttpServletResponse response) throws Exception
{
     try
     {
        response.setHeader("Content-Type", "text/event-stream");//必须
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("Expires",0);
        String serverDateTime = "data:"+CommanUtil.getCurrentDatetime()+"\n\n";//必须以data:开头;以\n\n结尾
        return serverDateTime;
    }
    catch(Exception e)
    {
        logger.debug(e.getMessage().toString());
        return e.getMessage().toString();
    }

}

----------------------------------------------------------------------------

如果数据比较长时,可以采用多行data:然后js客户端使用event.data.split('\n').join('')组合数据