本文介绍了如何等待 WebSocket 的 readyState 更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个带有轮询回退的 WebSocket.如果 WebSocket 连接成功,readyState 变为 1,但如果失败,readyState 为 3,我应该开始轮询.

I'm trying to implement a WebSocket with a fallback to polling. If the WebSocket connection succeeds, readyState becomes 1, but if it fails, readyState is 3, and I should begin polling.

我尝试过这样的事情:

var socket = new WebSocket(url);
socket.onmessage = onmsg;
while (socket.readyState == 0)
{
}
if (socket.readyState != 1)
{
    // fall back to polling
    setInterval(poll, interval);
}

我期待 socket.readyState 异步更新,并允许我立即读取它.但是,当我运行它时,我的浏览器死机了(我在放弃之前让它打开了大约半分钟).

I was expecting socket.readyState to update asynchronously, and allow me to read it immediately. However, when I run this, my browser freezes (I left it open for about half a minute before giving up).

我以为可能有一个 onreadyStateChanged 事件,但我在 MDN 参考中没有看到.

I thought perhaps there was an onreadyStateChanged event, but I didn't see one in the MDN reference.

我应该如何实施?显然,空循环不起作用,并且没有事件.

How should I be implementing this? Apparently an empty loop won't work, and there is no event for this.

推荐答案

这很简单,而且效果很好...您可以添加有关最大时间的条件,或尝试使其更健壮的次数...

This is simple and it work perfectly... you can add condition about maximal time, or number of try to make it more robust...

function sendMessage(msg){
    // Wait until the state of the socket is not ready and send the message when it is...
    waitForSocketConnection(ws, function(){
        console.log("message sent!!!");
        ws.send(msg);
    });
}

// Make the function wait until the connection is made...
function waitForSocketConnection(socket, callback){
    setTimeout(
        function () {
            if (socket.readyState === 1) {
                console.log("Connection is made")
                if (callback != null){
                    callback();
                }
            } else {
                console.log("wait for connection...")
                waitForSocketConnection(socket, callback);
            }

        }, 5); // wait 5 milisecond for the connection...
}

这篇关于如何等待 WebSocket 的 readyState 更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 12:21