fix: duplicate websocket connection

This commit is contained in:
hamster1963 2024-12-06 17:12:30 +08:00 committed by hi2hi
parent b8e08f3dd1
commit 5f719d5e5a

View File

@ -1,5 +1,11 @@
class WSService {
constructor(options) {
// 确保单例模式
if (WSService.instance) {
return WSService.instance;
}
WSService.instance = this;
const {
wsUrl,
onConnect,
@ -19,7 +25,7 @@ class WSService {
message: onMessage || (() => {}),
messageError: onMessageError || (() => {}),
};
// 0: 未连接1: 已连接,-1: 已关闭
// 0: 未连接1: 连接中2: 已连接,-1: 已关闭
this.connected = 0;
this.ws = undefined;
this.evt = (event) => {
@ -40,20 +46,25 @@ class WSService {
}
get isConnected() {
return this.connected === 1;
return this.connected === 2;
}
active() {
if (this.connected === 1) {
throw new Error('已创建连接,请勿重复创建');
if (this.connected !== 0) {
console.warn('WebSocket connection already exists or is connecting');
return;
}
// 标记为正在连接中
this.connected = 1;
// 创建 WebSocket 连接
this.ws = new WebSocket(this.$wsUrl);
this.ws.addEventListener('open', (event) => {
if (this.debug) {
console.log('socket connected', event);
}
this.connected = 1;
this.connected = 2;
this.$on.connect(event);
});
this.ws.addEventListener('close', (event) => {
@ -61,6 +72,7 @@ class WSService {
console.log('socket closed', event);
}
this.connected = -1;
WSService.instance = null; // 清除实例引用
this.$on.close(event);
});
this.ws.addEventListener('message', this.evt);