如何等待WebSocket的readyState更改 [英] How to wait for a WebSocket's readyState to change

查看:1582
本文介绍了如何等待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();
                }
                return;

            } else {
                console.log("wait for connection...")
                waitForSocketConnection(socket, callback);
            }

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆