在WebSocket.send
OPEN
中,它说:
抛出异常
的 INVALID_STATE_ERR
该连接目前不是CONNECTING
。
在CLOSED
状态下确实抛出异常,但如果套接字已关闭(状态为var s = null;
function log(msg) {
var d = document.createElement('div');
d.textContent = (new Date().toLocaleTimeString()) +": " + msg;
document.getElementById('out').appendChild(d);
}
function create() {
log("Creating");
s = new WebSocket("wss://echo.websocket.org");
s.onopen = function() {
log("Socket opened");
}
s.onmessage = function(e) {
log("Got: " + e.data);
}
send("before open");
}
function send(msg) {
try {
log("Sending: " + msg);
s.send(msg);
log("Send didn't throw");
}
catch(e) {
log("Exception: " + e.message);
}
}
function close() {
log("Closing");
s.close();
}
document.getElementById('create').addEventListener('click', create, true);
document.getElementById('send').addEventListener('click', send.bind(null, 'manually'), true);
document.getElementById('close').addEventListener('click', close, true);
),那么我不会得到任何异常。对于我尝试过的所有浏览器都会发生这种情况。
我试过阅读MDN documentation,但似乎找不到任何相关内容。
这是一些复制代码:
<button id="create">Create</button>
<button id="send">Send</button>
<button id="close">Close</button>
<div id="out"/>
{{1}}