Sending websocket ping/pong frame from browser

前端 未结 3 1477
广开言路
广开言路 2020-11-28 03:03

I keep reading about ping/pong messages in websockets to keep the connection alive, but I\'m not sure what they are. Is it a distinct frame type? (I don\'t see any methods

3条回答
  •  盖世英雄少女心
    2020-11-28 03:34

    a possible solution in js

    In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

    1. client sends a custom ping message, to keep alive by using the keepAlive function

    2. server ignore the ping message and response a custom pong message

    var timerID = 0; 
    function keepAlive() { 
        var timeout = 20000;  
        if (webSocket.readyState == webSocket.OPEN) {  
            webSocket.send('');  
        }  
        timerId = setTimeout(keepAlive, timeout);  
    }  
    function cancelKeepAlive() {  
        if (timerId) {  
            clearTimeout(timerId);  
        }  
    }
    
    

提交回复
热议问题