How to wait for a WebSocket's readyState to change

后端 未结 9 2350
梦如初夏
梦如初夏 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:18

    Here is a more elaborate explanation. First off, check the specific browser API, as not all browsers will be on the latest RFC. You can consult the

    You don't want to run a loop to constantly check the readystate, it's extra overhead you don't need. A better approach is to understand all of the events relevant to a readystate change, and then wire them up appropriately. They are as follows:

    onclose An event listener to be called when the WebSocket connection's readyState changes to CLOSED. The listener receives a CloseEvent named "close".

    onerror An event listener to be called when an error occurs. This is a simple event named "error".

    onmessage An event listener to be called when a message is received from the server. The listener receives a MessageEvent named "message".

    onopen An event listener to be called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".

    JS is entirely event driven, so you need to just wire up all of these events and check for the readystate, this way you can switch from WS to polling accordingly.

    I recommend you look at the Mozilla reference, it's easier to read than the RFC document and it will give you a good overview of the API and how it works (link).

    Don't forget to do a callback for a retry if you have a failure and poll until the callback for a successful reconnect is fired.

提交回复
热议问题