最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML5 Websocket wait for connection and readystate change before sending message - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

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!');
});

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)...
发布评论

评论列表(0)

  1. 暂无评论