SpringMVC实现服务器端推送

基于SSE(服务器端发送事件)的服务器端推送。(相似于ajax轮询)javascript

当咱们须要使用server向浏览器主动推送数据的时候,请考虑使用该项技术,而不是考虑具备双向通信功能的websocket;css

代码实现html

jsp:java

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>管理员登陆</title>
</head>
<body>
<div id="msgFromServerPush"></div>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
    ;$(function () {
        if(!!window.EventSource){
            console.log("support……");
            var source=new EventSource('/admin/push/'+new Date().getMilliseconds());
            s = '';
            source.addEventListener('message', function(e) {
                s += e.data + "<br/>";
                $("#msgFromServerPush").html(s);
            });//添加客户端的监听
            source.addEventListener('open', function(e) {
                console.log("链接打开");
            }, false);

            source.addEventListener('error',function(e){
                if(e.readyState==EventSource.CLOSED){
                    console.log("链接关闭");
                }else{
                    console.log(e.readyState);
                }
            });

        }else {
            console.log("not support……");
        }
    });
</script>
</body>
</html>

控制器:jquery

@RequestMapping(value = "push/{id}",produces = "text/event-stream")
    @ResponseBody
    public String push(@PathVariable String id){
        System.out.println("id"+id);
        Random r=new Random();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "data:server push data "+id+"-------------"+r.nextInt()+"\n\n";
    }

注意:return data: 这个是固定的。web

这样服务器会同时互不干扰的向两个窗口推送数据ajax

相关文章
相关标签/搜索