data() {
return {
websock: '',
reconnectTimer: '', // 重连定时器
pageDestroyed: false, // 页面是否销毁
websocketIsJump: false, // websocket 心跳是否正常
websocketTime: null, // websocket 定时器
linkWebsocketCount: 1, // websocket连接次数,超过3 断开连接
}
}
initWebSocket() {
this.websocketTime && clearInterval(this.websocketTime);
if(this.linkWebsocketCount > 3) { // 连续重连3次失败不再继续连接
return
}
this.linkWebsocketCount = this.linkWebsocketCount + 1
this.websock = new WebSocket(url); // URL —— websocket服务器地址
this.websock.onopen = this.websocketOnopen;
this.websock.onerror = this.websocketOnerror;
this.websock.onmessage = this.websocketOnmessage;
this.websock.onclose = this.websocketOnclose;
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常
window.onbeforeunload = function(){
if(websocket) {
console.log('关闭窗口')
this.websock.close();
}
};
},

- websocket 对象创建完成,会触发open方法,在该方法中调用心跳函数,确保websocket正常连接
websocketOnopen(e) {
this.linkWebsocketCount = 1 // 进入该方法表示能与服务器连接,连接次数置为1
this.heartCheck()
console.log('websocketOnopen',e)
},
- 连接失败或者连接出错会触发close、error方法,一般在这两个方法中放重连函数
websocketOnerror(e) {
this.reconnect() // 重连函数
console.log('websocketOnerror',e)
},
websocketOnclose() {
console.log('websocketOnclose')
if(!this.pageDestroyed) { // 如果是页面销毁时手动关闭的则不掉重连函数,看自己需求
this.reconnect()
}
},
// 重连函数
reconnect() {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = setTimeout(()=>{
this.websock = ''
this.initWebSocket()
},3000)
},
- 心跳函数,每隔一段时间向后端ping一个数据,能接收到返回的数据表示连接正常,收不到则表示已经断开连接,需重连
//心跳检测
heartCheck() {
var serverTimeoutObj = null
this.websocketTime && clearInterval(this.websocketTime);
serverTimeoutObj && clearTimeout(serverTimeoutObj);
this.websocketTime = setInterval(()=>{
// console.log('心跳函数,发送ping')
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常 websocketIsJump 置为true,3s 后若websocketIsJump还为false,则表示后端未返消息,已断开连接,需重连
this.websocketIsJump = false
this.websock.send('ping')
serverTimeoutObj = setTimeout(() => {
// console.log('判断是否有消息过来:',this.websocketIsJump)
if(!this.websocketIsJump) {
clearInterval(this.websocketTime)
this.websock = ''
this.initWebSocket()
// this.websock.close();
}
}, 3000);
}, 6000)
},
- message 方法 (服务器向客户端主动发消息会触发该方法)
websocketOnmessage(e) {
this.websocketIsJump = true
// console.log('websocket返回的数据',e)
},