Исправление проблемы нескольких одновременных попыток подключения по WebSocket
This commit is contained in:
@@ -1,3 +1,5 @@
|
|||||||
|
import * as utils from '../share/utils';
|
||||||
|
|
||||||
const cleanPeriod = 60*1000;//1 минута
|
const cleanPeriod = 60*1000;//1 минута
|
||||||
|
|
||||||
class WebSocketConnection {
|
class WebSocketConnection {
|
||||||
@@ -9,6 +11,8 @@ class WebSocketConnection {
|
|||||||
this.messageQueue = [];
|
this.messageQueue = [];
|
||||||
this.messageLifeTime = messageLifeTime;
|
this.messageLifeTime = messageLifeTime;
|
||||||
this.requestId = 0;
|
this.requestId = 0;
|
||||||
|
|
||||||
|
this.connecting = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
addListener(listener) {
|
addListener(listener) {
|
||||||
@@ -53,14 +57,22 @@ class WebSocketConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
open(url) {
|
open(url) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => { (async() => {
|
||||||
|
//Ожидаем окончания процесса подключения, если open уже был вызван
|
||||||
|
let i = 0;
|
||||||
|
while (this.connecting && i < 200) {//10 сек
|
||||||
|
await utils.sleep(50);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i >= 200)
|
||||||
|
this.connecting = false;
|
||||||
|
|
||||||
|
//проверим подключение, и если нет, то подключимся заново
|
||||||
if (this.ws && this.ws.readyState == WebSocket.OPEN) {
|
if (this.ws && this.ws.readyState == WebSocket.OPEN) {
|
||||||
resolve(this.ws);
|
resolve(this.ws);
|
||||||
} else {
|
} else {
|
||||||
let protocol = 'ws:';
|
this.connecting = true;
|
||||||
if (window.location.protocol == 'https:') {
|
const protocol = (window.location.protocol == 'https:' ? 'wss:' : 'ws:');
|
||||||
protocol = 'wss:'
|
|
||||||
}
|
|
||||||
|
|
||||||
url = url || `${protocol}//${window.location.host}/ws`;
|
url = url || `${protocol}//${window.location.host}/ws`;
|
||||||
|
|
||||||
@@ -72,10 +84,9 @@ console.log('new connection');
|
|||||||
}
|
}
|
||||||
this.timer = setTimeout(() => { this.periodicClean(); }, cleanPeriod);
|
this.timer = setTimeout(() => { this.periodicClean(); }, cleanPeriod);
|
||||||
|
|
||||||
let resolved = false;
|
|
||||||
this.ws.onopen = (e) => {
|
this.ws.onopen = (e) => {
|
||||||
console.log(this.ws.readyState);
|
console.log(this.ws.readyState);
|
||||||
resolved = true;
|
this.connecting = false;
|
||||||
resolve(e);
|
resolve(e);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -99,11 +110,13 @@ console.log(this.ws.readyState);
|
|||||||
|
|
||||||
this.ws.onerror = (e) => {
|
this.ws.onerror = (e) => {
|
||||||
this.emit(e.message, true);
|
this.emit(e.message, true);
|
||||||
if (!resolved)
|
if (this.connecting) {
|
||||||
|
this.connecting = false;
|
||||||
reject(e);
|
reject(e);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
})() });
|
||||||
}
|
}
|
||||||
|
|
||||||
//timeout в минутах (cleanPeriod)
|
//timeout в минутах (cleanPeriod)
|
||||||
|
|||||||
Reference in New Issue
Block a user