我刚刚开始学习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
我错过了重要的事情吗?
答案 0 :(得分:11)
打开连接后,即可开始向服务器传输数据。
等待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();
}
&#13;
答案 1 :(得分:0)
如果在service.onopen()之外使用Websocket()。send(),则仍然可以在发送消息之前检查readyState,如下所示:
websocket.sendmessage = async function(msg) {
while (this.readyState === 0) {
await sleep(200);
}
this.send(msg);
};