I am using Websockets in my React app, and I have to connect to a web socket and then sent a message as soon as it gets connected. but my code do not works in sync
Here it is
ws = new WebSocket(uri);
ws.send('my msg');
Is there a way to wait for connection established and ready state changed! Thanks!
I am using Websockets in my React app, and I have to connect to a web socket and then sent a message as soon as it gets connected. but my code do not works in sync
Here it is
ws = new WebSocket(uri);
ws.send('my msg');
Is there a way to wait for connection established and ready state changed! Thanks!
Share Improve this question asked May 19, 2017 at 8:00 h_hh_h 1,2314 gold badges28 silver badges47 bronze badges2 Answers
Reset to default 5From the docs on MDN:
// Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.addEventListener('open', function (event) { socket.send('Hello Server!'); });
I am doing the following to prepare my WebSocket for use in many other places, not just immediately after the WebSocket readyState changes:
// https://stackoverflow./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)...