initWebSocket () { // 初始化weosocket
this.destroyWebSocket()
try {
console.log('连接websocket')
const wsuri = 'ws://' + this.dataM.split('/')[2] + '?pageId=' + generateUUID()// ws地址
this.webSocket = new WebSocket(wsuri)
this.webSocket.onopen = (event) => {
console.log('send:' + this.currSceneInfo.id)
this.webSocket.send(this.currSceneInfo.id)
this.heartCheck.start(this.webSocket) // 心跳
}
this.webSocket.onmessage = (event) => {
if (event.data === 'HeartBeat') {
console.log('收到了心跳检测')
this.heartCheck.start(this.webSocket) // 心跳
} else {
const data = JSON.parse(event.data)
}
}
this.webSocket.onerror = () => {
console.log('发生异常了')
this.reconnect() // 重连
}
this.webSocket.onclose = (event) => {
console.log('断线重连')
this.reconnect() // 重连
}
} catch (e) {
console.log(e.message)
this.reconnect()
}
},
destroyWebSocket () {
if (this.webSocket) {
this.webSocket.onclose = (event) => {
console.log('链接关闭')
}
this.webSocket.close()
this.webSocket = null
}
},
destroyed () {
this.destroyWebSocket()
},
reconnect () {
if (this.lockReconnect) {
return
}
this.lockReconnect = true
// 没连接上会一直重连,设置延迟避免请求过多
this.tt && clearTimeout(this.tt)
this.tt = setTimeout(() => {
this.initWebSocket()
this.lockReconnect = false
}, 4000)
},