How to wait for a WebSocket's readyState to change

后端 未结 9 2351
梦如初夏
梦如初夏 2020-11-30 00:54

I\'m trying to implement a WebSocket with a fallback to polling. If the WebSocket connection succeeds, readyState becomes 1, but if it fails, readyState

9条回答
  •  不知归路
    2020-11-30 01:13

    I am not using pooling at all. Instead, I use queuing. First I create new send function and a queue:

    var msgs = []
    function send (msg) {
      if (ws.readyState !== 1) {
        msgs.push(msg)
      } else {
        ws.send(msg)
      }
    }
    

    Then I need to read and send when the connection is first established:

    function my_element_click () {
      if (ws == null){
        ws = new WebSocket(websocket_url)
        ws.onopen = function () {
          while (msgs.length > 0) {
            ws.send(msgs.pop())
          }
        }
        ws.onerror = function(error) {
          // do sth on error
        }
      } 
      msg = {type: 'mymessage', data: my_element.value}
      send(JSON.stringify(msg))
    }
    

    WebSocket connection in this example is created only on the first click. Usually, on second messages start to be sent directly.

提交回复
热议问题