首页 > 解决方案 > 具有不同 URL 的多个 websocket 连接

问题描述

我在同时连接到具有不同 URL 的多个 WebSocket 时遇到问题。到目前为止,我使用以下方法从 URL 连接到给定的套接字(一次一个)或向其中一个发送消息并在该Send()方法之后立即断开连接,然后创建一个新的。在这种情况下,我需要监听一些(未预定义的)套接字并接收到我的主题的消息。不幸的是,为了创建每个新链接,我必须提供一个新 URL。如何做到这一点,这样您就不会丢失以前的连接,并且所有内容都被一个 Observable(主题)收听?

在这里,我有一个功能,首先我需要将数据获取到数组(因此数量可能不同),然后打开数组中的尽可能多的连接:

组件.ts

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

接下来,我的方法中有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();
  }
}

所以在这个例子中,我需要打开连接:

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

并在可行的情况下从所有到一个 Observable 接收消息?

标签: javascriptangularwebsocketrxjs

解决方案


推荐阅读