SignalR“withAutomaticReconnect”问题

问题描述 投票:0回答:1

满足我的条件后,如何使用AutomaticReconnect处理或销毁它?无论我尝试什么,该方法每次都会执行。

const connection = new signalR.HubConnectionBuilder()
      .withUrl(socketServerUrl, {
        withCredentials: false,
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets,
      })
      .withAutomaticReconnect({
        nextRetryDelayInMilliseconds: ({ elapsedMilliseconds }) => {
          // function content
        },
      })
      .configureLogging(signalR.LogLevel.Information)
      .build();

    if (isGameSessionExpired) {
      // Looking for something like that, but didn't work
      connection.stop();
      connection.withAutomaticReconnect(null);
      connection = null;
    }
javascript signalr.client asp.net-core-signalr
1个回答
0
投票

需要注意的是,一旦

connection
被声明为
const
,就不能将其重新分配给
null

我刚刚优化了代码,一切正常,你可以尝试一下。

let allowReconnect = true; // allow reconnect by default

const connection = new signalR.HubConnectionBuilder()
  .withUrl(socketServerUrl, {
    withCredentials: false,
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets,
  })
  .withAutomaticReconnect({
    nextRetryDelayInMilliseconds: ({ elapsedMilliseconds }) => {
      if (!allowReconnect) {
        return null; // don't reconnect any more
      }
      // other logic here if you have
    },
  })
  .configureLogging(signalR.LogLevel.Information)
  .build();

if (isGameSessionExpired) {
  allowReconnect = false; // update the allowReconnect flag to prevent the reconnect behavior
  connection.stop(); // stop the connection
}
© www.soinside.com 2019 - 2024. All rights reserved.