Javascript HTML5 Websocket在发送消息之前等待连接和readystate更改
我在React应用程序中使用WebSocket,我必须连接到一个web套接字,然后在它连接后立即发送消息。但是我的代码不同步 给你Javascript HTML5 Websocket在发送消息之前等待连接和readystate更改,javascript,reactjs,websocket,Javascript,Reactjs,Websocket,我在React应用程序中使用WebSocket,我必须连接到一个web套接字,然后在它连接后立即发送消息。但是我的代码不同步 给你 ws = new WebSocket(uri); ws.send('my msg'); 是否有方法等待连接建立和就绪状态更改! 谢谢 来自: 我正在做以下工作来准备我的WebSocket,以便在许多其他地方使用,而不仅仅是在WebSocket readyState更改之后: // https://stackoverflow.com/questions/951021
ws = new WebSocket(uri);
ws.send('my msg');
是否有方法等待连接建立和就绪状态更改!
谢谢 来自:
我正在做以下工作来准备我的WebSocket,以便在许多其他地方使用,而不仅仅是在WebSocket readyState更改之后:
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// (inside of async function)...
const ws = new WebSocket(<webSocketServerUri>);
let timeToConnect = 0;
while (ws.readyState !== ws.OPEN) {
await sleep(1);
++timeToConnect;
};
console.log('The WebSocket took ' + timeToConnect + ' milliseconds to connect.');
// (inside of async function)...
// ...
// (some other place in the code where 'ws' is accessible)...
ws.send('my msg');
// (some other place in the code where 'ws' is accessible)...
//https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
常数睡眠=(毫秒)=>{
返回新承诺(resolve=>setTimeout(resolve,ms));
};
//(异步函数内部)。。。
const ws=new WebSocket();
设timeToConnect=0;
while(ws.readyState!==ws.OPEN){
等待睡眠(1);
++连接时间;
};
log('连接WebSocket需要'+timeToConnect+'毫秒');
//(异步函数内部)。。。
// ...
//(代码中可以访问“ws”的其他位置)。。。
ws.send('my msg');
//(代码中可以访问“ws”的其他位置)。。。
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// (inside of async function)...
const ws = new WebSocket(<webSocketServerUri>);
let timeToConnect = 0;
while (ws.readyState !== ws.OPEN) {
await sleep(1);
++timeToConnect;
};
console.log('The WebSocket took ' + timeToConnect + ' milliseconds to connect.');
// (inside of async function)...
// ...
// (some other place in the code where 'ws' is accessible)...
ws.send('my msg');
// (some other place in the code where 'ws' is accessible)...