From c95667eafbe7f92181281025aad5abac9bebce2b Mon Sep 17 00:00:00 2001 From: MingLiang Wang Date: Fri, 13 Jan 2023 17:16:15 +0800 Subject: [PATCH] fix: fix reconnect logic (#730) --- .../src/provider/affine/channel.ts | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/packages/data-center/src/provider/affine/channel.ts b/packages/data-center/src/provider/affine/channel.ts index 1503a8b450..da9e81c35e 100644 --- a/packages/data-center/src/provider/affine/channel.ts +++ b/packages/data-center/src/provider/affine/channel.ts @@ -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); + } } }); }