首先 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)
- },
来源: https://www.cnblogs.com/qisimx/p/10518355.html