我是javascript的新手并希望使用websockets。当我创建一个Websocket对象并尝试发送它时,我收到以下错误:
InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
所以我用下面的闭包解决了这个问题。这是解决我问题的合理方法吗?有更好的方法吗?我的方法的一个问题是,如果有人后来重新分配ws.onopen
的价值。我使用redux,所以我会在向后端发送请求时使用我的发送。我也在使用ES6,webpack和node.js.
const ws = new WebSocket("ws://echo.websocket.org/");
ws.onmessage = msg => console.log(msg);
const send = (()=>{
const queue = [];
ws.onopen = () => queue.forEach(msg => ws.send(msg));
return (msg) => {
if(ws.readyState === ws.OPEN){
ws.send(msg);
}
else{
queue.push(msg);
}
};
})();
send("foo");
send("bar");