javascript – websocket对象上的InvalidStateError

前端之家收集整理的这篇文章主要介绍了javascript – websocket对象上的InvalidStateError前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚开始学习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

我错过了重要的事吗?

解决方法

Once you’ve opened your connection,you can begin transmitting data to the server.

等待onopen事件!

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();
}
原文链接:https://www.f2er.com/js/151144.html

猜你在找的JavaScript相关文章