websocket 客户端抛错 INVALID_STATE_ERR
在做websocket的时候,服务器连接正常但是客户端总是抛出错误:socket.send(msg) INVALID_STATE_ERR: DOM Exception 11
经过测试判断是send()这里出的问题。但是实在不知到是什么问题,服务器状态如下:
[info]init...
[info]init end
[info]have connected peer 0
[info]socket_select...
[info]socket_select end
[info]readable socket:1
[info]writeable socket:1
[info]accept...
[info]accept end
[info]Resource id #8 CONNECTED
[info]have connected peer 0
[info]socket_select...
希望有人可以帮忙看看,具体代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WebSocket Client</title>
<style>
html,body{font:normal 0.9em arial,helvetica;}
#log {width:440px; height:200px; border:1px solid #7F9DB9; overflow:auto;}
#msg {width:330px;}
</style>
<script>
var socket;
function init(){
var host = "ws://127.0.0.1:12345/WebSoket2/server.php";
try{
socket = new WebSocket(host);
log('WebSocket - status '+socket.readyState);
socket.onopen = function(msg){ log("Welcome - status "+this.readyState); };
socket.onmessage = function(msg){ log("Received: "+msg.data); };
socket.onclose = function(msg){ log("Disconnected - status "+this.readyState); };
}
catch(e) {
log(e);
}
$("msg").focus();
}
function send(){
var txt,msg;
txt = $("msg");
msg = txt.value;
if(!msg){ alert("Message can not be empty"); return; }
txt.value="";
txt.focus();
log(socket);
try{ socket.send(msg); log('Sent: '+msg); } catch(ex){ log("send error: " + ex); }
}
function quit(){
log("Goodbye!");
socket.close();
socket=null;
}
// Utilities
function $(id){ return document.getElementById(id); }
function log(msg){ $("log").innerHTML+="<br>"+msg; }
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>
</head>
<body onload="init()">
<h3>WebSocket</h3>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">Send</button>
<button onclick="quit()">Quit</button>
</body>
</html>
正经的看片绅士
12 years ago
Answers
我也遇到同样的问题。这应该是服务器端的问题吧
很明显socket协议握手失败了,服务器端的问题
我做了一个简单的服务器端,你可以测试一下
https://github.com/duguying/rocket
定位Moyan
answered 12 years ago