前端網絡監控與斷網重鏈

業務背景

最近在作大屏數據可視化項目得時候,在思考項目交付和運行狀況得時候,考慮到了須要在公司大屏顯示器上面展現,忽然想到了項目可能面臨斷網及其網速慢得狀況下得一下展現問題,所以做爲專欄進行這兩個問題得講解前端

問題一 WebSocket 在網絡終端和從新聯網後自動連接

知識點: 理解WebSocket心跳及重連機制web

在使用websocket的過程當中,有時候會遇到網絡斷開的狀況,可是在網絡斷開的時候服務器端並無觸發onclose的事件。這樣會有:服務器會繼續向客戶端發送多餘的連接,而且這些數據還會丟失。因此就須要一種機制來檢測客戶端和服務端是否處於正常的連接狀態。所以就有了websocket的心跳了。還有心跳,說明還活着,沒有心跳說明已經掛掉了。segmentfault

    • 爲何叫心跳包呢?
      它就像心跳同樣每隔固定的時間發一次,來告訴服務器,我還活着。
    • 心跳機制是?

    心跳機制是每隔一段時間會向服務器發送一個數據包,告訴服務器本身還活着,同時客戶端會確認服務器端是否還活着,若是還活着的話,就會回傳一個數據包給客戶端來肯定服務器端也還活着,不然的話,有多是網絡斷開鏈接了。須要重連~後端

    那麼須要怎麼去實現它呢?以下全部代碼:api

    let ws = null,
        wsUrl = "ws://xxx/rest/api/websocket",
        lockReconnect = false,
        tt = null,
        that = this;
        function MonitorWebSocket(wsUrl){
            this.timeout = 3000;
            this.timeoutObj = null;
            this.serverTimeoutObj= null;
            
            try {
                ws = new WebSocket(wsUrl);
                this.init(wsUrl);
            } catch(e) {
                console.log('catch');
                this.reconnect(wsUrl);
            }
        }
        MonitorWebSocket.prototype.init = function (wsUrl) {
            ws.onopen = () => {
                 //心跳檢測重置
                that.navigatorStatus()
                // console.log("client:打開鏈接-心跳檢測開啓");
                this.heartCheckStart();
            };
            ws.onmessage = e => {
                // 拿到任何消息都說明當前鏈接是正常的
                // console.info('onmessage---->接收到消息');
                this.heartCheckStart();
                that.list = JSON.parse(e.data).data;
                that.list.todayData && that.$emit("changePointStatus",that.list.todayData)    
            };
            ws.onclose = params => {
                // console.log('連接關閉');
                this.reconnect(wsUrl);
            };
            ws.onerror = function(e) {
                // console.log('發生異常了');
                this.reconnect(wsUrl);
            };
        }
        MonitorWebSocket.prototype.reconnect = function(wsUrl) {
            if(lockReconnect) {
                return;
            };
            lockReconnect = true;
            //沒鏈接上會一直重連,設置延遲避免請求過多
            tt && clearTimeout(tt);
            tt = setTimeout(function () {
                (function(){
                    // console.info("從新鏈接")
                    new MonitorWebSocket(wsUrl);
                })()
                lockReconnect = false;
            }, 5000);
        }
        MonitorWebSocket.prototype.heartCheckStart = function() {
            // console.log('心跳檢測開始');
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function(){
                //這裏發送一個心跳,後端收到後,返回一個心跳消息,
                // console.log('啓動心跳');
                ws.send("test");
                this.serverTimeoutObj = setTimeout(function() {
                    ws.close();
                }, this.timeout);
    
            }, this.timeout)
        }
        let linkMarket = new MonitorWebSocket(wsUrl);

    概括與總結

    實現心跳檢測的思路是:每隔一段固定的時間,向服務器端發送一個ping數據,若是在正常的狀況下,服務器會返回一個pong給客戶端,若是客戶端經過
    onmessage事件能監聽到的話,說明請求正常,這裏咱們使用了一個定時器,每隔3秒的狀況下,若是是網絡斷開的狀況下,在指定的時間內服務器端並無返回心跳響應消息,所以服務器端斷開了,所以這個時候咱們使用ws.close關閉鏈接,在一段時間後(在不一樣的瀏覽器下,時間是不同的,firefox響應更快),
    能夠經過 onclose事件監聽到。所以在onclose事件內,咱們能夠調用 reconnect事件進行重連操做。跨域

    問題二 如何建立一個Javascript頁面來檢測用戶的互聯網速度並在頁面上顯示它?

    知識點: 網速測試方法得核心思想瀏覽器

    無論經過什麼方式,通常都是經過下載一個文件,而後用文件的大小除以所耗時間,就是你的本地網絡速度了。服務器

    這裏介紹的是一個最常被使用的,又是最簡單的方法。websocket

    let speed = {
        status: 3,
    },
    that = this;
    function Network () {
        this.speedInterval = null;
        this.networkInterval = null;
        this.reNetworkInterval = null;
        this.time = 5000;
        this.speedStauts = null;
        this.getConnectState = function() {
            return navigator.onLine ? 1 : 0;
        }
        this.getSpeedStauts = function(){
        return this.speedStauts;
        }
    }
    // 網絡速度檢測
    Network.prototype.startSpeed = function (){
        window.clearInterval(this.speedInterval);
        this.speedInterval = null;
        let that = this;
        if(this.getConnectState() == 1){
            this.speedInterval = window.setInterval(function(){
                let start = new Date().getTime();
                if(that.getConnectState() == 1){
                    let img = document.getElementById("networkSpeedImage");
                    try{
                    img.src = "http://www.baidu.com/img/baidu_jgylogo3.gif?_t=" + new Date().getTime();
                    img.onload = function(){
                        let end = new Date().getTime();
                        let delta = end - start;
                        console.info("delta====>",delta)
                        if (delta > 200) {
                        console.info("湊活")
                        speed.status= 1;
                        } else if (delta > 100) {
                        speed.status = 2;
                        } else {
                        speed.status = 3;
                        }             
                        console.info("statusSpeed====>",speed.status)             
                    }
                    } catch {
                        speed.status = 0;
                        console.info("網絡斷開")
                    }
                }else {
                    speed.status = 0;
                    console.info("網絡斷開2")
                }
            },this.time)
        }else {
            speed.status = 0;
            console.info("網絡斷開1")
        }
    }
    let netWork = new Network();

    總結

    經過建立img對象,設置onload監聽回調,而後指定src, 一旦指定src,圖片資源就會加載,完成時onload回調就會調用,咱們能夠根據時機分別標記start和end。網絡

    前端判斷網速的方法及其優缺點

    • img加載測速:藉助img對象加載測算網速。優勢:沒有跨域帶來的問題。缺點:(1)要本身測文件大小並提供參數fileSize,(2)文件必須爲圖片 (3)文件大小不能靈活控制
    • Ajax測速: 經過Ajax測算網速。 優勢: (1)不用提供文件大小參數,由於能夠從response首部得到(2)測試的文件不必定要是圖片,且數據量能靈活控制。缺點:跨域問題
    • downlink測速: 經過navigator.connection.downlink讀取網速。優勢:不須要任何參數。缺點:1.兼容性頗有問題,2.帶寬查詢不是實時的,具備分鐘級別的時間間隔
      已上都是能夠三中方法均可以實現,你們能夠考慮個子得項目進行合理得選擇

    圖片

    相關文章
    相關標籤/搜索