websocket中遇到的问题

记录websocket中遇到的各种问题

app.js:1 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

这个错误有可能的原因是该WebSocket对象正在发送问题,发送还没结束,然后调用者又调用了send方法接着继续发送,所以still in connecting,解决这个问题的方法是通过判断readyStatus延时发送

file


send(111)

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);
    }
};

stackoverflow