+
95
-

回答

以下是vue版本的一个websocket重连机制,代码如下:

<!DOCTYPE html>

<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />

<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1.js"></script>


</head>

<body>
<div id="app">



</div>
<script>
let websock = null;
let socketTimer = null;
let socketParam = {
type: 'test'
};
new Vue({
el: '#app',
name: 'test',
data () {
return {
socketUrl: 'ws://web.debug.only.bfw.wiki:9502',
timerWS: null, // 用于ws重连
timerCountWS: 0, // 用于重连计数,0-立刻开始重连,非0-1min重连一次。
timerFlagWS: true // 跳转页面了不再重连
}
},
mounted () {
this.initWebsocket()
},
destroyed () {
// 关闭websocket
this.timerFlagWS = false;
this.timerCountWS = 0;
clearTimeout(this.timerWS)
if (websock !== null) {
websock.close();
websock = null;
}
clearTimeout(socketTimer);
},
methods: {
initWebsocket () {
if (typeof WebSocket !== 'undefined') {
this.timerCountWS++;
// 浏览器支持Websocket通信协议 开启长连接
websock = new WebSocket(this.socketUrl)
websock.onopen = this.websocketonopen
websock.onclose = this.websocketclose
websock.onerror = this.websocketonerror
websock.onmessage = this.websocketonmessage
} else {
// 浏览器不支持Websocket通信协议
this.$message.info('当前浏览器不支持Websocket通信协议,建议使用Chrome或者Firefox浏览器!')
}
},
// 开启
websocketonopen () {
console.log('websocketonopen [test]');
this.timerCountWS = 0;
this.threadPoxi();
},
// 关闭
websocketclose (e) {
console.log(e, 'websocketclose [test]');
let self = this;
if (self.timerCountWS === 0) {
if (self.timerFlagWS && e.code === 1006) self.initWebsocket();
console.log('websocket reconnect:[test ' + self.timerCountWS + ']', self.timerFlagWS);
} else {
clearTimeout(self.timerWS);
self.timerWS = setTimeout(() => {
if (self.timerFlagWS && e.code === 1006) self.initWebsocket();
console.log('websocket reconnect:[test ' + self.timerCountWS + ']', self.timerFlagWS);
}, 60000)
}
},
// 错误
websocketonerror (e) {
console.log('websocketonerror [test]');
},
// 数据接收
websocketonmessage (e) {
let res = JSON.parse(e.data)
console.log(res, 'websocket推送结果');
},
threadPoxi () {
// 参数
let self = this;
// 若是ws开启状态
if (websock.readyState === websock.OPEN) {
console.log('websock.OPEN, websock.send start... [test]');
self.websocketsend(socketParam)
} else if (websock.readyState === websock.CONNECTING) {
// 若是正在开启状态 则等待300毫秒 再调threadPoxi判断状态
console.log('websock.CONNECTING, please wait 300ms... [test]');
clearTimeout(socketTimer)
socketTimer = setTimeout(() => {
self.threadPoxi();
}, 300)
} else {
// 若未开启 初始化websocket
console.log('websock is not open, wait for reboot... [test]');
self.initWebSocket();
}
},
// 数据发送
websocketsend (param) {
websock.send(JSON.stringify(param));
}
}
});
</script>
</body>

</html>


网友回复

我知道答案,我要回答