如果一段时间没有收到Websocket,请刷新页面

问题描述 投票:3回答:1

我有一个页面,接收到websocket后,它会通过javascript进行操作。我希望仅在上次与我希望的时间之间未收到websocket的情况下,才能在一段时间后重新加载此页面。

<script>
        if ("WebSocket" in window) {

            var ws = new WebSocket('ws://192.168.33.1:5000');
            var variableSpan = document.getElementById('variable');

            ws.onmessage = function (event) {
                var message = JSON.parse(event.data);
                console.log(message);
                jQuery('#variable').empty();

                $(function () {
                    $.get(message.variable, function (data) {
                        $("#variable").append(data);
                    });
                });

                setTimeout(function () {
                    window.location.reload(); // you can pass true to reload function to ignore the client cache and reload from the server
                }, 10000);
            }
        }
</script>

我尝试过类似的操作,但似乎不起作用。我会感谢您的帮助:)

javascript jquery websocket page-refresh
1个回答
0
投票

检查webSocket状态后重新加载

function onWebSocketClosed(){

    if (webSocket.readyState != WebSocket.OPEN) {
        try{
            console.error("webSocket is not open: " + webSocket.readyState +"Reloading Page");
            window.location.reload()
        }
        catch (error) {
            console.log('onWebSocketClosed :  {0}' , error)
        }
    }       
}

© www.soinside.com 2019 - 2024. All rights reserved.