給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{
        。。。。
        }
   }

   

參考轉載來源:https://blog.csdn.net/jkxqj/article/details/77848466


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM