HTML5 Websocket在发送消息之前等待连接和readystate更改

时间:2017-05-19 08:00:47

标签: javascript reactjs websocket

我在我的React应用程序中使用Websockets,我必须连接到Web套接字,然后在连接后立即发送消息。但是我的代码不能同步工作

这是

ws = new WebSocket(uri);
ws.send('my msg');

有没有办法等待连接建立和就绪状态改变! 谢谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我正在做以下准备,以准备在许多其他地方使用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)...