【发布时间】:2022-01-14 21:59:12
【问题描述】:
我有一个 Angular / ASP.net 应用程序,我最近在其中使用 WebSockets 实现了 SignalR-Communication。到目前为止,通信工作正常,但是通过查看页面的网络连接,我得到的印象是有时会打开几个 websocket 连接。页面重新加载时可能会发生这种情况,但我不确定。
这些连接中的每一个都以 ws:// 开头,并且具有不同的 sec-websocket-accept 标头,所以这些都是打开的连接吧?
这是从根组件调用的函数:
private setUpSignalR() {
if(SignalRService.isConnected)
return;
this.signalRService.startConnection();
this.signalRService.addPushNotificationListener();
}
在 SignalRService-Class 内部:
public startConnection = () => {
const protocol = window.location.protocol.replace('http://', 'ws://').replace('http://', 'ws://');
const host = window.location.host;
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${protocol}//${host}/apphub`,{
accessTokenFactory: () => this._settings.authorization?.access_token ,
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
this.hubConnection
.start()
.then(() => {
console.log('SinalR HubConnection started');
SignalRService.isConnected = true;
})
.catch(err => console.log('Error while starting connection: ' + err))
this.hubConnection.onclose(() => {
SignalRService.isConnected = false;
setTimeout(() => {
this.hubConnection.start().then(() => {
console.log("reconnected");
SignalRService.isConnected = true;
}).catch(err => console.log(err));
}, 5000);
});
我认为设置和读取 isConnected 标志就足够了,但它仍然会打开更多连接。任何想法如何确保不会发生这种情况?
【问题讨论】:
标签: angular signalr asp.net-core-signalr