mirror of
https://github.com/hi2shark/nazhua.git
synced 2026-01-17 09:40:42 +08:00
fix: duplicate websocket connection
This commit is contained in:
parent
b8e08f3dd1
commit
5f719d5e5a
@ -1,5 +1,11 @@
|
|||||||
class WSService {
|
class WSService {
|
||||||
constructor(options) {
|
constructor(options) {
|
||||||
|
// 确保单例模式
|
||||||
|
if (WSService.instance) {
|
||||||
|
return WSService.instance;
|
||||||
|
}
|
||||||
|
WSService.instance = this;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
wsUrl,
|
wsUrl,
|
||||||
onConnect,
|
onConnect,
|
||||||
@ -19,7 +25,7 @@ class WSService {
|
|||||||
message: onMessage || (() => {}),
|
message: onMessage || (() => {}),
|
||||||
messageError: onMessageError || (() => {}),
|
messageError: onMessageError || (() => {}),
|
||||||
};
|
};
|
||||||
// 0: 未连接,1: 已连接,-1: 已关闭
|
// 0: 未连接,1: 连接中,2: 已连接,-1: 已关闭
|
||||||
this.connected = 0;
|
this.connected = 0;
|
||||||
this.ws = undefined;
|
this.ws = undefined;
|
||||||
this.evt = (event) => {
|
this.evt = (event) => {
|
||||||
@ -40,20 +46,25 @@ class WSService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get isConnected() {
|
get isConnected() {
|
||||||
return this.connected === 1;
|
return this.connected === 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
active() {
|
active() {
|
||||||
if (this.connected === 1) {
|
if (this.connected !== 0) {
|
||||||
throw new Error('已创建连接,请勿重复创建');
|
console.warn('WebSocket connection already exists or is connecting');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 标记为正在连接中
|
||||||
|
this.connected = 1;
|
||||||
|
|
||||||
// 创建 WebSocket 连接
|
// 创建 WebSocket 连接
|
||||||
this.ws = new WebSocket(this.$wsUrl);
|
this.ws = new WebSocket(this.$wsUrl);
|
||||||
this.ws.addEventListener('open', (event) => {
|
this.ws.addEventListener('open', (event) => {
|
||||||
if (this.debug) {
|
if (this.debug) {
|
||||||
console.log('socket connected', event);
|
console.log('socket connected', event);
|
||||||
}
|
}
|
||||||
this.connected = 1;
|
this.connected = 2;
|
||||||
this.$on.connect(event);
|
this.$on.connect(event);
|
||||||
});
|
});
|
||||||
this.ws.addEventListener('close', (event) => {
|
this.ws.addEventListener('close', (event) => {
|
||||||
@ -61,6 +72,7 @@ class WSService {
|
|||||||
console.log('socket closed', event);
|
console.log('socket closed', event);
|
||||||
}
|
}
|
||||||
this.connected = -1;
|
this.connected = -1;
|
||||||
|
WSService.instance = null; // 清除实例引用
|
||||||
this.$on.close(event);
|
this.$on.close(event);
|
||||||
});
|
});
|
||||||
this.ws.addEventListener('message', this.evt);
|
this.ws.addEventListener('message', this.evt);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user