From c0f1f7b3692d12098590291ec9a414ed4d54dcfe Mon Sep 17 00:00:00 2001 From: Lei OT Date: Tue, 16 Jan 2024 16:37:49 +0800 Subject: [PATCH] WebSocketLib 1 --- src/lib/websocketLib.js | 65 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/lib/websocketLib.js diff --git a/src/lib/websocketLib.js b/src/lib/websocketLib.js new file mode 100644 index 0000000..b91895b --- /dev/null +++ b/src/lib/websocketLib.js @@ -0,0 +1,65 @@ +// websocketLib.js +import { WebSocketSubject } from 'rxjs/webSocket'; +import { retryWhen, delay, take, catchError } from 'rxjs/operators'; +import { throwError } from 'rxjs'; + +class WebSocketLib { + constructor(url, authToken) { + this.url = url; + this.authToken = authToken; + } + + connect() { + this.socket$ = new WebSocketSubject({ + url: this.url, + protocol: this.authToken, // Using the protocol parameter for authentication + openObserver: { + next: () => { + console.log('Connection established'); + }, + }, + closeObserver: { + next: () => { + console.log('Connection closed'); + }, + }, + }); + + this.socket$ + .pipe( + retryWhen(errors => + errors.pipe( + delay(1000), // Retry connection every 1 second + take(10), // Maximum of 10 retries + catchError(error => throwError(`Failed to reconnect: ${error}`)) // Throw error after 10 failed retries + ) + ) + ) + .subscribe( + msg => console.log('Received message:', msg), + err => console.error('Received error:', err), + () => console.log('Connection closed') + ); + } + + sendMessage(message) { + if (!this.socket$) { + console.error('Must connect to WebSocket server before sending a message'); + return; + } + + this.socket$.next({ type: 'message', content: message }); + } + + disconnect() { + if (!this.socket$) { + console.error('Must connect to WebSocket server before disconnecting'); + return; + } + + this.socket$.complete(); + this.socket$ = null; + } +} + +export default WebSocketLib;