h5项目开发中,出现ios在手机锁屏后websocket连接断掉的问题,解决方法是在mounted生命周期中监听页面呼出事件,在页面呼出状态中判断websocket的连接状态,当websocket处于未连接状态时,重新连接websocket
mounted () { document.addEventListener(‘visibilitychange‘, () => { if (!document.hidden) {//页面呼出 if (this.websocket.readyState === 2 || this.websocket.readyState === 3) { this.createWebSocket() } } }) }
websocket状态如下:
根据readyState属性可以判断webSocket的连接状态,该属性的值可以是下面几种:
0 :对应常量CONNECTING (numeric value 0),
正在建立连接连接,还没有完成。The connection has not yet been established.
1 :对应常量OPEN (numeric value 1),
连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
2 :对应常量CLOSING (numeric value 2)
连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
3 : 对应常量CLOSED (numeric value 3)
连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.