首页 新闻 会员 周边 捐助

使用 ASP.NET Core SignalR 时经常出现连接错误

0
悬赏园豆:30 [已解决问题] 解决于 2025-09-07 08:14

下面的前端 typescript 代码

import { HubConnection, HubConnectionBuilder, HubConnectionState } from '@microsoft/signalr';

export class WechatMpQrComponent implements OnInit {  
  private connection: HubConnection;

  constructor() {}

  ngOnInit(): void {
    this.connection = new HubConnectionBuilder()
      .withUrl(`${environment.baseUrl}/hubs/wechat-mp-auth`)
      .build();  
  }

  async start(): Promise<void> {
    if (this.connection.state !== HubConnectionState.Disconnected) {
      return;
    }

    this.status = WechatMpQrStatus.Loading;
    try {
      await this.connection.start();
      await this.connection.send('Initialize');
    } catch (e) {
      this.onError(`建立连接失败 ${(e as Error)?.message}`);
    }
  }
}

经常出现下面的错误

建立连接失败:Unable to connect to the server with any of the available transports. WebSockets failed: Error: There was an error with the transport. ServerSentEvents failed: Error: Error occurred LongPolling failed: Error
dudu的主页 dudu | 高人七级 | 园豆:24779
提问于:2025-09-07 06:43
< >
分享
最佳答案
0

在创建 HubConnection 时将 skipNegotiation 设置为 true 解决了

this.connection = new HubConnectionBuilder()
    .withUrl(`${environment.baseUrl}/hubs/wechat-mp-auth`, {
      skipNegotiation: true,
      transport: HttpTransportType.WebSockets
    })
    .build();

Negotiation 需要用到粘滞会话(Sticky Sessions),而我们使用的阿里云传统型负载均衡 CLB 不支持 Sticky Sessions

参考:

dudu | 高人七级 |园豆:24779 | 2025-09-07 08:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册