未捕获的InvalidStateError:无法执行'发送' on' WebSocket':仍处于连接状态

时间:2014-04-14 03:20:21

标签: javascript exception-handling websocket

当我的页面加载时,我尝试send向服务器发送消息以启动连接,但它无法正常工作。此脚本块位于我的文件顶部附近:

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

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

  

Uncaught InvalidStateError:无法在'WebSocket'上执行'send':仍处于CONNECTING状态

所以我尝试catch例外情况,如下所示,但现在似乎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进行测试。

4 个答案:

答案 0 :(得分:24)

您可以通过代理函数发送消息,该函数等待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

答案 1 :(得分:6)

发生此错误的原因是,您在建立WebSocket连接之前发送消息

您可以通过执行以下操作来解决它:

conn.onopen = () => conn.send("Message");

onopen 功能会在发送消息之前等待您建立网络套接字连接。

答案 2 :(得分:0)

如果您使用一个websocket客户端对象并从随机应用程序位置连接,则对象可以处于连接模式(concurent访问)。

如果您只想通过一个websoket进行交换 使用promise创建类并将其保存在属性

class Ws {
  get newClientPromise() {
    return new Promise((resolve, reject) => {
      let wsClient = new WebSocket("ws://demos.kaazing.com/echo");
      console.log(wsClient)
      wsClient.onopen = () => {
        console.log("connected");
        resolve(wsClient);
      };
      wsClient.onerror = error => reject(error);
    })
  }
  get clientPromise() {
    if (!this.promise) {
      this.promise = this.newClientPromise
    }
    return this.promise;
  }
}

创建单身人士

window.wsSingleton = new Ws()

在app的任何地方使用clientPromise属性

window.wsSingleton.clientPromise
  .then( wsClient =>{wsClient.send('data'); console.log('sended')})
  .catch( error => alert(error) )

http://jsfiddle.net/adqu7q58/11/

答案 3 :(得分:0)

使用异步函数

我有另一个想法,在连接套接字时解决承诺:

await waitForConnection();
ws.send(data);

实施

这个技巧是使用解析器数组实现的。

let ws = new WebSocket(url);

let connection_resolvers = [];
let waitForConnection = () => {
    return new Promise((resolve, reject) => {
        if (ws.readyState === WebSocket.OPEN) {
            resolve();
        }
        else {
            connection_resolvers.push({resolve, reject});
        }
    });
}

ws.addEventListener('open', () => {
    connection_resolvers.forEach(r => r.resolve())
});