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