我刚开始学习 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/