首先new一个webscoket的连接
let noticeSocketLink = new WebSocket(‘webSocket的地址’)
这里是连接成功之后的操作
linkNoticeWebsocket(){ noticeSocketLink.onopen = ()=>{ //在连接成功打开的时候调用断线重连的函数,传入websocket对象 webCloseLink(noticeSocketLink) } this.noticeSocketLink.onmessage = res => {
console.log("res")
} 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)
},