Closing WebSocket correctly (HTML5, Javascript)

后端 未结 5 1885
悲哀的现实
悲哀的现实 2020-11-28 02:13

I am playing around with HTML5 WebSockets. I was wondering, how do I close the connection gracefully? Like, what happens if user refreshes the page, or just closes the brows

5条回答
  •  自闭症患者
    2020-11-28 03:17

    As mentioned by theoobe, some browsers do not close the websockets automatically. Don't try to handle any "close browser window" events client-side. There is currently no reliable way to do it, if you consider support of major desktop AND mobile browsers (e.g. onbeforeunload will not work in Mobile Safari). I had good experience with handling this problem server-side. E.g. if you use Java EE, take a look at javax.websocket.Endpoint, depending on the browser either the OnClose method or the OnError method will be called if you close/reload the browser window.

提交回复
热议问题