How do i know if connection is alive with websockets?

前端 未结 2 669
太阳男子
太阳男子 2020-12-08 20:41

I have a webapp, which is running in a browser. That webapp is connected to a server, which uses websockets. So the communication between the server and my client/browser is

相关标签:
2条回答
  • 2020-12-08 21:02

    A websocket connection object has a readyState field which will tell you if the connection is still active (from the dart documentation). The readyState can be either

    0 - connection not yet established
    1 - conncetion established
    2 - in closing handshake
    3 - connection closed or could not open
    

    You can also define an event handler for the websocket close event if this is something you'd like to handle (try to reconnect, etc).

    0 讨论(0)
  • 2020-12-08 21:04

    3 ways:

    • rely on TCP to detect loss of connectivity, which will ultimately pop up in JS onclose event
    • send WebSocket pings from server .. browsers will reply with WS pongs, loss of connectivity is probably more robustly detected also on client side
    • send app level heartbeats from browser to server, server need to have logic to reply. you can't trigger WS pings from browsers (in JS)
    0 讨论(0)
提交回复
热议问题