WebSocketLib 1
parent
b86fcd993a
commit
c0f1f7b369
@ -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;
|
Loading…
Reference in New Issue