fix: fix reconnect logic (#730)

This commit is contained in:
MingLiang Wang
2023-01-13 17:16:15 +08:00
committed by GitHub
parent 2c1eee1194
commit c95667eafb

View File

@@ -3,13 +3,13 @@ import { Logger } from 'src/types';
import { token } from './apis/token';
import * as url from 'lib0/url';
const RECONNECT_INTERVAL_TIME = 5000;
const RECONNECT_INTERVAL_TIME = 500;
const MAX_RECONNECT_TIMES = 50;
export class WebsocketClient extends websocket.WebsocketClient {
public shouldReconnect = false;
private _reconnectInterval: number | null = null;
private _logger: Logger;
private _retryTimes = 0;
constructor(
serverUrl: string,
logger: Logger,
@@ -34,30 +34,28 @@ export class WebsocketClient extends websocket.WebsocketClient {
this.on('connect', () => {
this._logger('Affine channel connected');
this.shouldReconnect = true;
if (this._reconnectInterval) {
window.clearInterval(this._reconnectInterval);
}
this._retryTimes = 0;
});
this.on('disconnect', ({ error }: { error: Error }) => {
if (error) {
let times = 0;
// Try reconnect if connect error has occurred
this._reconnectInterval = window.setInterval(() => {
if (this.shouldReconnect && token.isLogin && !this.connected) {
try {
this.connect();
this._logger(`try reconnect channel ${++times} times`);
if (times > MAX_RECONNECT_TIMES) {
if (this.shouldReconnect && token.isLogin && !this.connected) {
try {
setTimeout(() => {
if (this._retryTimes <= MAX_RECONNECT_TIMES) {
this.connect();
this._logger(
`try reconnect channel ${++this._retryTimes} times`
);
} else {
this._logger('reconnect failed, max reconnect times reached');
this._reconnectInterval &&
window.clearInterval(this._reconnectInterval);
}
} catch (e) {
this._logger('reconnect failed', e);
}
}, RECONNECT_INTERVAL_TIME);
} catch (e) {
this._logger('reconnect failed', e);
}
}, RECONNECT_INTERVAL_TIME);
}
}
});
}