在使用WebSocket时有时会报出这样的错误:
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state
这个错误有可能的原因是该WebSocket对象正在发送问题,发送还没结束,然后调用者又调用了send方法接着继续发送,所以still in connecting,解决这个问题的方法是通过判断readyStatus延时发送:
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);
}
};