javascript - Websocket 对象上的 InvalidStateError

标签 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

我是不是漏掉了什么重要的东西?

最佳答案

The WebSocket.onopen property is an EventHandler that is called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data.

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

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

关于javascript - Websocket 对象上的 InvalidStateError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857272/

相关文章:

angularjs - Node Js Angular cli,ng 服务错误,套接字关闭

javascript - 如何访问 Controller 内的 url 参数?

javascript - Paul Irish,他是怎么做到的?

javascript - 仅在页面加载时检索一次数据

java - 使WebSocket发送非阻塞

Laravel 与 socket.io 的回声

scala - Scala Play 中的状态是如何管理的! 2.0 网络套接字?

javascript - jQuery UI 自动完成 : Disable tab completion?

javascript - 即使值相同,条件测试也会失败

python - 如何使用 WebSocket 在 Web 浏览器页面中显示 asyncio 的值