gpt4 book ai didi

javascript - Websocket 对象上的 InvalidStateError

转载 作者:数据小太阳 更新时间:2023-10-29 05:05:22 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com