websocket对象上的InvalidStateError

时间:2016-06-16 11:01:14

标签: javascript websocket

我刚刚开始学习websockets,我得到一个奇怪的错误:

<script type="text/javascript">
    window.onload = function(){
        var service = new WebSocket("ws://localhost:8080/websocket/test"); 
        service.onmessage = function(event){
            alert("message"); 
        } 
        service.onopen = function(){
            service.send("hello!");
        } 
        service.onclose = function(){
            alert("closed"); 
        } 
        service.onerror = function(){
            alert("error"); 
        }

        service.send("test");
        service.close();
    }

</script>

就行:

            service.send("test");

我明白了:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

我错过了重要的事情吗?

2 个答案:

答案 0 :(得分:11)

  

打开连接后,即可开始向服务器传输数据。

等待onopen活动!

&#13;
&#13;
window.onload = function() {
  var service = new WebSocket("wss://echo.websocket.org");
  service.onmessage = function(event) {
    alert("onmessage event: "+event.data);
  }
  service.onopen = function() {
    service.send("test"); //Will work here!
    //^^^^^^^^^^^^^^^^^
    service.send("hello!");
  }
  service.onclose = function() {
    alert("closed");
  }
  service.onerror = function() {
    alert("error");
  }

  //Can't close while a connection is still being established.
  //service.close();
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果在service.onopen()之外使用Websocket()。send(),则仍然可以在发送消息之前检查readyState,如下所示:

    websocket.sendmessage = async function(msg) {
       while (this.readyState === 0) {
            await sleep(200);
       }
       this.send(msg);
    };