javascript - 具有不同 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 接收消息?
解决方案
推荐阅读
- typescript - IDE 以 TypeScript 格式识别 Cucumber 步骤
- asp.net-mvc - 在 DropDownListFor html 帮助程序中选择默认值不起作用 - ASP .NET MVC
- java - 线程“主”java.lang.IndexOutOfBoundsException 中的 Netbeans 异常:索引:2,大小:2
- python - 单击时 Tkinter 窗口崩溃,可能是由于无限循环。Python 3.7.1
- config - BizTalk 配置疑难解答
- python - Python:如何根据字符串中单词的数量将字符串拆分为变量?
- css - Div Previous Siblings 没有减小它的大小
- python - python中多个wav文件的降噪
- c# - 如何删除列表中重复的项目
- python - 如何塑造多元数据以输入到 LSTM