问题描述
当我的页面加载时,我尝试向服务器发送一条消息到发送
以发起连接,但是它不起作用。此脚本块位于我的文件顶部:
When my page loads, I try to send
a message to the server to initiate a connection, but it's not working. This script block is near the top of my file:
var connection = new WrapperWS();
connection.ident();
// var autoIdent = window.addEventListener('load', connection.ident(), false);
大多数情况下,我看到标题中的错误:
Most of the time, I see the error in the title:
所以我试图 catch
的异常,你可以看到下面,但现在看起来似乎 InvalidStateError
没有定义,并且产生一个 ReferenceError
。
So I tried to catch
the exception, as you can see below, but now it seems InvalidStateError
is not defined and that produces a ReferenceError
.
这是我的websocket连接的包装对象:
Here's the wrapper object for my websocket connection:
// Define WrapperWS
function WrapperWS() {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://server:8000/");
var self = this;
ws.onopen = function () {
console.log("Opening a connection...");
window.identified = false;
};
ws.onclose = function (evt) {
console.log("I'm sorry. Bye!");
};
ws.onmessage = function (evt) {
// handle messages here
};
ws.onerror = function (evt) {
console.log("ERR: " + evt.data);
};
this.write = function () {
if (!window.identified) {
connection.ident();
console.debug("Wasn't identified earlier. It is now.");
}
ws.send(theText.value);
};
this.ident = function () {
var session = "Test";
try {
ws.send(session);
} catch (error) {
if (error instanceof InvalidStateError) {
// possibly still 'CONNECTING'
if (ws.readyState !== 1) {
var waitSend = setInterval(ws.send(session), 1000);
}
}
}
window.identified = true;
theText.value = "Hello!";
say.click();
theText.disabled = false;
};
};
}
我正在使用Ubuntu上的Chromium进行测试。
I am testing using Chromium on Ubuntu.
推荐答案
您可以通过等待readyState为1的代理功能发送消息。
You could send messages via a proxy function that waits for the readyState to be 1.
this.send = function (message, callback) {
this.waitForConnection(function () {
ws.send(message);
if (typeof callback !== 'undefined') {
callback();
}
}, 1000);
};
this.waitForConnection = function (callback, interval) {
if (ws.readyState === 1) {
callback();
} else {
var that = this;
// optional: implement backoff for interval here
setTimeout(function () {
that.waitForConnection(callback, interval);
}, interval);
}
};
然后使用 this.send
代替 ws.send
,并将之后运行的代码放在回调中:
Then use this.send
in place of ws.send
, and put the code that should be run afterwards in a callback:
this.ident = function () {
var session = "Test";
this.send(session, function () {
window.identified = true;
theText.value = "Hello!";
say.click();
theText.disabled = false;
});
};
对于更精简的内容,您可以查看。
For something more streamlined you could look into promises.
这篇关于未捕获InvalidStateError:无法在“WebSocket”上执行“send”:仍处于CONNECTING状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!