給websocket加入心跳包防止自動斷開連接

var userId=$("#userId").val();
var lockReconnect = false;  //避免ws重複連接
var ws = null;          // 判斷當前瀏覽器是否支持WebSocket
var wsUrl = serverConfig.cyberhouse_ws+userId;
createWebSocket(wsUrl);   //連接ws

function createWebSocket(url) {
    try{
        if('WebSocket' in window){
            ws = new WebSocket(url);
        }else if('MozWebSocket' in window){  
            ws = new MozWebSocket(url);
        }else{
            layui.use(['layer'],function(){
              var layer = layui.layer;
              layer.alert("您的瀏覽器不支持websocket協議,建議使用新版谷歌、火狐等瀏覽器,請勿使用IE10以下瀏覽器,360瀏覽器請使用極速模式,不要使用兼容模式!"); 
            });
        }
        initEventHandle();
    }catch(e){
        reconnect(url);
        console.log(e);
    }     
}

function initEventHandle() {
    ws.onclose = function () {
        reconnect(wsUrl);
        console.log("llws連接關閉!"+new Date().toUTCString());
    };
    ws.onerror = function () {
        reconnect(wsUrl);
        console.log("llws連接錯誤!");
    };
    ws.onopen = function () {
        heartCheck.reset().start();      //心跳檢測重置
        console.log("llws連接成功!"+new Date().toUTCString());
    };
    ws.onmessage = function (event) {    //如果獲取到消息,心跳檢測重置
        heartCheck.reset().start();      //拿到任何消息都說明當前連接是正常的
        console.log("llws收到消息啦:" +event.data);
        if(event.data!='pong'){
            var obj=eval("("+event.data+")");
            layui.use(['layim'], function(layim){
                if(obj.type=="onlineStatus"){
                    layim.setFriendStatus(obj.id, obj.content);
                }else if(obj.type=="friend" || obj.type=="group"){
                    layim.getMessage(obj);  
                } 
    };
}
// 監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function() {
    ws.close();
}  

function reconnect(url) {
    if(lockReconnect) return;
    lockReconnect = true;
    setTimeout(function () {     //沒連接上會一直重連,設置延遲避免請求過多
        createWebSocket(url);
        lockReconnect = false;
    }, 2000);
}

//心跳檢測
var heartCheck = {
    timeout: 540000,        //9分鐘發一次心跳
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
            //這裏發送一個心跳,後端收到後,返回一個心跳消息,
            //onmessage拿到返回的心跳就說明連接正常
            ws.send("ping");
            console.log("ping!")
            self.serverTimeoutObj = setTimeout(function(){//如果超過一定時間還沒重置,說明後端主動斷開了
                ws.close();     //如果onclose會執行reconnect,我們執行ws.close()就行了.如果直接執行reconnect 會觸發onclose導致重連兩次
            }, self.timeout)
        }, this.timeout)
    }
}
    // 收到客戶端消息後調用的方法 
    @OnMessage  
    public void onMessage(String message, Session session) {  
        if(message.equals("ping")){
        }else{
        。。。。
        }
   }

系統發現websocket每隔10分鐘自動斷開連接,搜了很多博客都說設置一下nginx的
keepalive_timeout
proxy_connect_timeout
proxy_send_timeout
proxy_read_timeout
這四個字段的時長即可,然而好像並不奏效。遂採取心跳包的方式每隔9分鐘客戶端自動發送ping消息給服務端,服務端不需要返回。即可解決問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章