javascript - 未捕获的 InvalidStateError : Failed to execute 'send' on 'WebSocket' : Still in CONNECTING state

标签 javascript exception-handling websocket

当我的页面加载时,我尝试向服务器发送 消息以启动连接,但它不起作用。这个脚本 block 靠近我的文件的顶部:

var connection = new WrapperWS();
connection.ident();
// var autoIdent = window.addEventListener('load', connection.ident(), false);

大多数时候,我会在标题中看到错误:

Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state

所以我尝试捕获异常,如下所示,但现在看来 InvalidStateError 未定义并且会产生 ReferenceError.

这是我的 websocket 连接的包装器对象:

// Define WrapperWS

function WrapperWS() {
    if ("WebSocket" in window) {
        var ws = new WebSocket("ws://server:8000/");
        var self = this;

        ws.onopen = function () {
            console.log("Opening a connection...");
            window.identified = false;
        };
        ws.onclose = function (evt) {
            console.log("I'm sorry. Bye!");
        };
        ws.onmessage = function (evt) {
            // handle messages here
        };
        ws.onerror = function (evt) {
            console.log("ERR: " + evt.data);
        };

        this.write = function () {
            if (!window.identified) {
                connection.ident();
                console.debug("Wasn't identified earlier. It is now.");
            }
            ws.send(theText.value);
        };

        this.ident = function () {
            var session = "Test";
            try {
                ws.send(session);
            } catch (error) {
                if (error instanceof InvalidStateError) {
                    // possibly still 'CONNECTING'
                    if (ws.readyState !== 1) {
                        var waitSend = setInterval(ws.send(session), 1000);
                    }
                }
            }
        window.identified = true;
            theText.value = "Hello!";
            say.click();
            theText.disabled = false;
        };

    };

}

我正在 Ubuntu 上使用 Chromium 进行测试。

最佳答案

您可以通过等待 readyState 为 1 的代理函数发送消息。

this.send = function (message, callback) {
    this.waitForConnection(function () {
        ws.send(message);
        if (typeof callback !== 'undefined') {
          callback();
        }
    }, 1000);
};

this.waitForConnection = function (callback, interval) {
    if (ws.readyState === 1) {
        callback();
    } else {
        var that = this;
        // optional: implement backoff for interval here
        setTimeout(function () {
            that.waitForConnection(callback, interval);
        }, interval);
    }
};

然后使用this.send代替ws.send,并将之后应该运行的代码放在回调中:

this.ident = function () {
    var session = "Test";
    this.send(session, function () {
        window.identified = true;
        theText.value = "Hello!";
        say.click();
        theText.disabled = false;
    });
};

对于更精简的内容,您可以查看 promises .

关于javascript - 未捕获的 InvalidStateError : Failed to execute 'send' on 'WebSocket' : Still in CONNECTING state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051416/

相关文章:

javascript - Angular UI Router - 使用 ui-sref 导航到动态状态时会出现双斜杠

c# - 编码 IDispatch 时出现 COM Interop 灾难性故障 (0x8000FFFF)

c# - 如何覆盖默认的未捕获异常对话框?

javascript - 在 Socket.IO 和 WS 之间共享 WebSocket 连接

google-chrome - google chrome实现的是哪个版本的websockets协议(protocol)草案

javascript - 如何在javascript中将HTML文件格式作为字符串

javascript - JS 在 iOS 设备上无法正常工作 - 仅有时

node.js - NodeJS SocketIO - 如何确保正在使用 websockets?

javascript - click 事件仅适用于双击而不是单击

c# - 应用程序级全局异常处理程序没有被命中