websocket使用及心跳检测
该websocket已经全部封装好了,可以直接拉到一个新文件中去进行使用,记得修改websocket地址
data() {
return {
lockReconnect: false,
websocket: null,
sendTimeoutObj: null,
serverTimeoutObj: null,
reconnectTimeoutObj: null,
}
}
methods: {
// 创建websocket
createSocket(){
console.log('初始化')
// 初始化重连判断
this.lockReconnect = false
// 实例化websocket
this.websocket = new WebSocket(`ws://xxxxxxxxx`,`request.header头,若需要token,可以将token写在此处`)
// 初始化websocket方法
this.init()
},
init(){
// websocket成功连接时的事件
this.websocket.onopen = ()=>{
console.log('open')
// websocket成功连接后,进行心跳检测,防止掉线
this.websocketonopen()
}
// websocket获取响应信息的事件
this.websocket.onmessage = (event)=>{
console.log(event,'onmessage')
this.websocketonmessage(event)
}
// websocket关闭时的事件
this.websocket.onclose = ()=>{
console.log('onclose')
this.websocketonclose()
}
// websocket异常时的事件
this.websocket.onerror = ()=>{
console.log('onerror')
this.websocketonerror()
}
},
// websocket建立连接
websocketonopen() {
// 心跳检测事件
this.heartCheckStart()
},
// websocket接受数据
websocketonmessage(event){
if(event.data == 'heartCheck'){
console.log('心跳正常连接')
}else {
console.log('获取到成功数据,关闭socket连接')
// 可以在次处判断event.data是否为我们想要的数据
// 若数据为我们需要的数据,则手动断开websocket
// 结束websocket
this.destroyWebSocket()
return
}
this.heartCheckStart()
},
// websocket关闭
websocketonclose(){
// 重新连接
this.reconnect()
},
// websocket报错
websocketonerror(){
// 重新连接
this.reconnect()
},
// 心跳检测
heartCheckStart(){
console.log('心跳检测启动')
let that = this
// 清理websocket.send定时器
that.sendTimeoutObj && clearTimeout(that.sendTimeoutObj)
// 清理服务器超时未响应定时器
that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj)
// 3s向websocket发送一条信息,检测连接是否正常
that.sendTimeoutObj = setTimeout(()=>{
// readyState为1,表示连接正常,发送检测消息给websocket
if(that.websocket.readyState==1){
console.log('用websocket发送检测测试')
that.websocket.send('heartCheck')
}
// 设置5s超时事件,若5s内未收到websocket响应信息,则重置websocket
that.serverTimeoutObj = setTimeout(()=>{
console.log('5s超时关闭sorket')
// 5s超时,手动关闭websocket
that.websocket.close()
},5000)
},3000)
},
// 重新连接
reconnect() {
// 若为手动关闭websocket,防止再次连接
if (this.lockReconnect) return
console.log('重新连接~~~~~~~~~~!!!!!!!!')
// 若websocket异常或者非法断开,两秒钟重连一次,直至重连成功
this.reconnectTimeoutObj = setTimeout(()=>{
this.websocket.close()
// websocket进行连接
this.createSocket()
},2000)
},
// 手动关闭websocket,不需要再次连接
destroyWebSocket() {
if (this.websocket) {
console.log('this.websocket.readyState====>');
// 手动设置为true,防止再次重连
this.lockReconnect = true
// 清理messagg.send定时器
clearTimeout(this.sendTimeoutObj)
// 清理服务器超时未响应定时器
clearTimeout(this.serverTimeoutObj)
// 清理重连定时器
clearTimeout(this.reconnectTimeoutObj)
this.sendTimeoutObj = null
this.serverTimeoutObj = null
this.reconnectTimeoutObj = null
// 手动断开websocket
this.websocket.close()
console.log('离开网页,关闭websock~~~~~~~~~~');
}
},
}
mounted() {
this.createSocket()
},
beforeDestroy() {
console.log('销毁')
this.destroyWebSocket()
}
本文含有隐藏内容,请 开通VIP 后查看