Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

77
Views
Multiple websocket connections with different URL

I have a problem connecting simultaneously to several WebSockets with different URLs. So far I used the following methods to connect to a given socket from the URL (one at a time) or send a message to one and disconnect immediately after the Send() method, and then create a new one. In this case I need to listen to some (not predefined) sockets and receive messages to my Subject. Unfortunately for creating each new link, I have to provide a new URL. How to do it so that you do not lose previous connections and that everything is listened to to one Observable (Subject)?

Here I have function where first I need to fetch data to array (so may be different amount), and then open as many connections as there are in the array:

component.ts

arrayIds = ['1abc', '2abc', '3abc'] // fetched data from API
...
startConnecting() {
  this.arrayIds.forEach( id => {
      this.websocketService.connect(id).subscribe();
    });
}

Next I have methods in my websocketService.service.ts:

websocketService.service.ts.ts

export class WebsocketService implements OnDestroy{
  connection$: WebSocketSubject<any>;
  RETRY_SECONDS = 10;
  constructor() { }

  connect(id: string): Observable<WebSocketSubject<any>> {
    return of(environment.WEBSOCKET_URL).pipe(
      filter(apiUrl => !!apiUrl),
      map(apiUrl => apiUrl + `/${id}/`),  // here I need update new socket URL
      switchMap(wsUrl => {
        if (this.connection$) {
          return this.connection$;
        } else {
          this.connection$ = webSocket(wsUrl);
          return this.connection$;
        }
      }),
      retryWhen((errors) => errors.pipe(delay(this.RETRY_SECONDS)))
    );
  }

  send(data): void {
    if (this.connection$) {
      this.connection$.next(data);
    } else {
      console.error('error');
    }
  }

  closeConnection(): void {
    if (this.connection$) {
      this.connection$.complete();
      this.connection$ = null;
    }
  }
  ngOnDestroy(): void {
    this.closeConnection();
  }
}

So in this example I need open connection with:

 1. ws://URL/1abc  
 2. ws://URL/2abc
 3. ws://URL/3abc

and receive messages from all to one Observable if this is posiible?

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.