Handling connection loss with websockets

前端 未结 4 1826
清酒与你
清酒与你 2020-12-07 10:32

I\'ve recently set-up a local WebSocket server which works fine, however I\'m having a few troubles understanding how I should handle a sudden loss of connection which neith

4条回答
  •  伪装坚强ぢ
    2020-12-07 10:33

    You have to add ping pong method

    Create a code in server when receive __ping__ send __pong__ back

    JavaScript code is give below

    function ping() {
            ws.send('__ping__');
            tm = setTimeout(function () {
    
               /// ---connection closed ///
    
    
        }, 5000);
    }
    
    function pong() {
        clearTimeout(tm);
    }
    websocket_conn.onopen = function () {
        setInterval(ping, 30000);
    }
    websocket_conn.onmessage = function (evt) {
        var msg = evt.data;
        if (msg == '__pong__') {
            pong();
            return;
        }
        //////-- other operation --//
    }
    

提交回复
热议问题