美文网首页
前端websocket心跳

前端websocket心跳

作者: 新篇章 | 来源:发表于2018-04-18 03:12 被阅读0次
//WebSocket心跳
var ws = '';
createWebSocket();
function createWebSocket() {
    try {
        ws = new WebSocket(websocketAdd);
        init();
    } catch(e) {
        console.log('catch');
        reconnect(websocketAdd);
    }
}

function reconnect(url) {
    if(lockReconnect) {
        return;
    };
    lockReconnect = true;
    //没连接上会一直重连,设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function() {
        createWebSocket(url);
        lockReconnect = false;
    }, 2000);
}

var heartCheck = {
    timeout: 10000, //60ms
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function() {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        this.start();
    },
    start: function() {
        var self = this;
        this.timeoutObj = setTimeout(function() {
            ws.send(JSON.stringify({
                "ping": 18212558000
            }));
            self.serverTimeoutObj = setTimeout(function() {
                ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    },
}

function init() {
    ws.onopen = function() {
        console.log("open")
        heartCheck.start();
    };
    ws.onmessage = function(event) {
        console.log("online")
        heartCheck.reset();
    }

    ws.onclose = function() {
        console.log("close")
        reconnect();
    };
    ws.onerror = function(err) {
        console.log("error");
        console,log(err);
        reconnect();
    };
}

//心跳end------------------------------

相关文章

网友评论

      本文标题:前端websocket心跳

      本文链接:https://www.haomeiwen.com/subject/bummkftx.html