2

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!

h_h
  • 1,101
  • 3
  • 24
  • 44

2 Answers2

3

From 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!');
});
user3297291
  • 19,011
  • 1
  • 24
  • 39
0

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.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)...
M. Hays
  • 11
  • 3