Client auto re-connect

This commit is contained in:
Yasin İLKAYA 2023-06-04 15:57:01 +03:00
parent 4ba04c6d4f
commit 5a85be59e5
3 changed files with 25 additions and 2 deletions

View File

@ -1,5 +1,8 @@
export interface IConnection{ export interface IConnection{
endpoint: string; endpoint: string;
autoReconnect?: boolean | {
timeout: number;
}
} }
export class Connection export class Connection
{ {
@ -7,11 +10,27 @@ export class Connection
public endpoint : URL; public endpoint : URL;
public autoPair : boolean = false; public autoPair : boolean = false;
public connected : boolean = false; public connected : boolean = false;
public autoReconnect : boolean = false;
public autoReconnectTimeout : number = 3000;
public autoReconnectTimer? : number;
constructor(options: IConnection){ constructor(options: IConnection){
this.endpoint = new URL(options.endpoint); this.endpoint = new URL(options.endpoint);
if(typeof options.autoReconnect == "boolean")
{
this.autoReconnect = true;
}else if(options.autoReconnect)
{
this.autoReconnect = true;
this.autoReconnectTimeout = options.autoReconnect.timeout;
}
} }
public connect() public connect()
{ {
if(this.autoReconnectTimer)
{
clearTimeout(this.autoReconnectTimer)
};
this.ws = new WebSocket(this.endpoint.href); this.ws = new WebSocket(this.endpoint.href);
this.addWSEvents(); this.addWSEvents();
} }
@ -36,6 +55,10 @@ export class Connection
private eventClose() private eventClose()
{ {
this.connected = false; this.connected = false;
if(this.autoReconnect)
{
this.autoReconnectTimer = setTimeout(this.connect, this.autoReconnectTimeout)
}
} }
private eventError() private eventError()
{ {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long