练习:使用springmvc实现H5(server-sent event)

1. 注意设置报头为 "text/event-stream"

2. \n\n必须要

3. 键必须为data

java代码:

@Controller  
@RequestMapping("/send")  
public class H5SendServer {  
    @RequestMapping(value = "/serverSend.do")  
    public void serverSend(HttpServletResponse response)  
    {  
        response.setContentType("text/event-stream");   
        response.setCharacterEncoding("UTF-8");  
        try {  
            PrintWriter writer = response.getWriter();  
            writer.write("data: 中文测试 \n\n");//这里需要\n\n,必须要,不然前台接收不到值,键必须为data
            writer.flush();  
              
            Thread.sleep(3000);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }   
    }  
}


js代码:

if(typeof(EventSource)!=="undefined"){
	var source=new EventSource(path+"/send/serverSend.do");
	source.onmessage = function(event){
		console.log("event.data=" + event.data);//必须用data接收
		$("#test").innerHTML += event.data + "
"; }; source.onerror = function(event){ console.log("error"); }; source.onopen = function(event){ console.log("open"); }; }else{ console.log("此浏览器不支持server-send"); }
实现效果:



你可能感兴趣的:(HTML,java)