47 lines
1.3 KiB
JavaScript
47 lines
1.3 KiB
JavaScript
import config from '@/config';
|
|
import { ref } from 'vue';
|
|
let socket;
|
|
let reconnectAttempts = 1;
|
|
const maxReconnectAttempts = 5;
|
|
export function createWebSocket() {
|
|
let socketurl = config.WEBSOCKET || null;
|
|
if (socketurl) {
|
|
try {
|
|
socket = new WebSocket(socketurl);
|
|
socket.onopen = function() {
|
|
console.log('WebSocket连接成功');
|
|
reconnectAttempts = 0; // reset reconnect attempts
|
|
}
|
|
socket.onerror = function() {
|
|
console.log('WebSocket连接发生错误');
|
|
reconnect();
|
|
}
|
|
socket.onclose = function() {
|
|
console.log('WebSocket连接关闭');
|
|
reconnect();
|
|
}
|
|
// 更新 socketState 的值
|
|
socketState.value = socket;
|
|
} catch (e) {
|
|
console.log('WebSocket连接失败', e);
|
|
reconnect();
|
|
}
|
|
}
|
|
}
|
|
|
|
function reconnect() {
|
|
if (maxReconnectAttempts > reconnectAttempts) {
|
|
setTimeout(function() {
|
|
createWebSocket();
|
|
console.log('WebSocket进行重连(' + reconnectAttempts);
|
|
reconnectAttempts++;
|
|
}, 2000);
|
|
} else {
|
|
console.log('WebSocket重连失败');
|
|
}
|
|
}
|
|
const socketState = ref(socket);
|
|
createWebSocket();
|
|
export default {
|
|
state: socketState
|
|
} |