【问题标题】:Angular SignalR opens several websocketsAngular SignalR 打开几个 websocket
【发布时间】: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


    【解决方案1】:

    当您的集线器尝试连接时,您的函数 setUpSignalR 可能会被多次调用,您还应该创建一个名为connecting 的变量并立即设置。然后在您的 if 语句中检查您是否正在连接或已连接。

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 2012-03-10
      相关资源
      最近更新 更多