标签:ready bsp 连接 else read notice mes 实现 ==
首先new一个webscoket的连接
this.noticeSocketLink = new WebSocket(‘webSocket的地址’)
这里是连接成功之后的操作
linkNoticeWebsocket(){
this.noticeSocketLink.onopen = ()=>{
在连接成功打开的时候调用断线重连的函数
this.webCloseLink(this.noticeSocketLink)
}
this.noticeSocketLink.onmessage = res => {}
this.noticeSocketLink.onclose = res => {
console.log("websocket is closed")
}
},
//断开连接,断线重连的函数
webCloseLink(WebSocketId){
WebSocketId.send("心跳包内容")
// 每个15秒发送一次心跳包
let hb = setInterval(()=>{
WebSocketId.send("心跳包内容")
// 检测到websocket连接断开
if(WebSocketId.readyState == 2 || WebSocketId.readyState == 3){
clearInterval(this.hb)
let i = 1
let myVar = setInterval(()=>{
if(WebSocketId.readyState == 2 || WebSocketId.readyState == 3){
// 重新new一个websocket的连接
this.noticeSocketLink = new WebSocket(WebSocketId.url);
WebSocketId = this.noticeSocketLink;
if(i == 5){
clearInterval(myVar);
// location.reload();
return
}
i++
}else if(WebSocketId.readyState == 0){
}else if(WebSocketId.readyState == 1){ // websocket重连成功
this.linkNoticeWebsocket();
clearInterval(hb)
clearInterval(myVar)
}
},4*1000)
}
}, 15000)
},
标签:ready bsp 连接 else read notice mes 实现 ==
原文地址:https://www.cnblogs.com/qisimx/p/10518355.html