WebSocket发送方法即使在onconnect之后尝试也会引发异常。 并非总是如此,但很多时候我在控制台中看到了记录的异常。
这是打字稿代码: -
open() {
if ('WebSocket' in window) {
this.ws = new WebSocket(ApiUrls.Socket(''));
this.ws.onopen = () => {
const authentication = {
msgType : 'Authenticate',
data : {
token : localStorage.getItem('authToken')
}
}
this.ws.send(JSON.stringify(authentication));
};
this.ws.onmessage = (evt) => {
// console.log(evt);
this.parseMessage(evt.data);
};
this.ws.onclose = () => {
this.connected = false;
// console.log('retrying connection with server');
if (localStorage.getItem('authToken')) {
this.reconnectTimeout = setTimeout(this.open.bind(this), 1000);
}
};
} else {
alert('WebSocket NOT supported by your Browser!');
}
}
控制台中的异常: -
ERROR DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
at WebSocket.ws.onopen [as __zone_symbol__ON_PROPERTYopen] (http://localhost:4200/main.bundle.js:5586:26)
at WebSocket.wrapFn (http://localhost:4200/polyfills.bundle.js:3711:39)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2970:31)
at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:87677:33)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2969:36)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2737:47)
at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.bundle.js:3044:34)
at invokeTask (http://localhost:4200/polyfills.bundle.js:4085:14)
at WebSocket.globalZoneAwareCallback (http://localhost:4200/polyfills.bundle.js:4111:17)
它太冗长,但有关的信息是ERROR DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
at WebSocket.ws.onopen [as __zone_symbol__ON_PROPERTYopen]
。
答案 0 :(得分:0)
当open方法被调用两次时,这会中断。在这种情况下,ws属性将被仍处于连接状态的新Websocket覆盖。然后在onopen处理程序中使用错误的WebSocket(它是异步的)。
{{1}}
答案 1 :(得分:0)
我发现这似乎有帮助:
gs://domain.com...
区别在于您使用触发onopen事件的websocket实例,而不是this.ws.onopen = (e) => {
// Not sure if the following line is necessary but doesn't hurt
if (e.target.readyState !== WebSocket.OPEN) return;
const authentication = {
msgType : 'Authenticate',
data : {
token : localStorage.getItem('authToken')
}
}
// Here's the key: use the websocket instance that triggered the onopen event
e.target.send(JSON.stringify(authentication));
}
变量中存在的实例,因为this.ws
同时可能发生了变化。