// ws 混入
export const websocket = {
data() {
return {
lockReconnect: false,
wsTimer: null,
heartTimer: null,
sendTime: 5
};
},
methods: {
// 尝试websocket
createWebSocket(url) {
try {
const ws = new WebSocket(url);
this.wsInit(ws, url);
} catch (error) {
this.reconnect(url);
}
},
// 初始化websocket
wsInit(ws, url) {
ws.onerror = () => {
this.reconnect(url);
};
ws.onopen = () => {
this.heartCheck(ws);
// console.log('websocket打开');
};
ws.onmessage = res => {
let info = JSON.parse(res.data);
if (info.data === '') {
return;
}
this.info = JSON.parse(res.data);
// console.log(JSON.parse(res.data));
};
ws.onclose = () => {
// 关闭 websocket
// console.log('连接已关闭...');
this.reconnect(url);
};
},
// 重连操作
reconnect(url) {
if (this.lockReconnect) {
return;
}
this.lockReconnect = true;
this.wsTimer && clearInterval(this.wsTimer);
this.wsTimer = setInterval(() => {
this.createWebSocket(url);
this.lockReconnect = false;
}, 4 * 1000);
},
// 心跳校验
heartCheck(ws) {
this.heartTimer = setInterval(() => {
ws.send('心跳监测');
// console.log('心跳校验');
this.sendTime--;
if (this.sendTime === 0) {
// console.log('没有收到服务器数据,链接断开,尝试重连');
this.reconnect();
}
}, 6 * 1000);
}
},
mounted() {
// this.createWebSocket('ws://192.168.8.59:8081/yszd/websocket/aa');
this.createWebSocket('ws://ieac.f3322.net:9013/yszd/websocket/aa');
}
};
websocket
最新推荐文章于 2023-04-12 01:52:16 发布