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

相關文章
相關標籤/搜索