You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.6KB

  1. import { Injectable } from '@angular/core';
  2. import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
  3. import {BehaviorSubject, catchError, delayWhen, Observable, retryWhen, Subject, tap, timer} from "rxjs";
  4. @Injectable({
  5. providedIn: 'root'
  6. })
  7. export class SocketService {
  8. gateway = 'ws:/socket.aztrace.vn/ws';
  9. websocket$!: WebSocketSubject<any> ;
  10. private isConnected: boolean = false;
  11. private messagesSubject$ = new Subject();
  12. public messages$ = this.messagesSubject$.asObservable();
  13. private statusSubject = new BehaviorSubject<boolean>(this.isConnected);
  14. public status$ = this.statusSubject.asObservable();
  15. constructor() {
  16. }
  17. public connect(cfg: { reconnect: boolean } = {reconnect: false}): void {
  18. if (!this.websocket$ || this.websocket$.closed) {
  19. console.log('Trying to open a WebSocket connection…');
  20. this.websocket$ = this.getNewWebSocket();
  21. this.websocket$.subscribe((messages) => {
  22. this.messagesSubject$.next(messages);
  23. });
  24. }
  25. }
  26. close() {
  27. this.websocket$.complete();
  28. }
  29. sendMessage(msg: any) {
  30. this.websocket$.next(msg);
  31. }
  32. private getNewWebSocket() {
  33. return webSocket({
  34. url: this.gateway,
  35. openObserver: {
  36. next: () => {
  37. console.log('Connection ok');
  38. this.isConnected = true;
  39. this.statusSubject.next(this.isConnected);
  40. }
  41. },
  42. closeObserver: {
  43. next: () => {
  44. console.log('Connection closed');
  45. this.isConnected = false;
  46. this.connect({reconnect: true});
  47. this.statusSubject.next(this.isConnected);
  48. }
  49. },
  50. });
  51. }
  52. }