2016-06-16 42 views
1

我剛開始學習的WebSockets,安迪得到一個奇怪的錯誤:InvalidStateError的WebSocket對象

<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 

上午我錯過了重要的事情?

回答

3

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

相關問題