超时后重新连接时,Azure SignalR StartAsync引发错误

时间:2019-08-27 16:04:40

标签: xamarin.forms signalr-hub signalr.client asp.net-core-signalr azure-signalr

我在Android的Xamarin应用程序上有一个简单的后台服务,在其中使用以下代码为我的Azure服务创建SignalR客户端:

 public async Task ConnectAsync(string assetId)
        {
            try
            {
                AssetId = assetId;
                if (connection == null)
                {
                    var client = new HttpClient();

                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("asset-id", assetId);

                    string negotiateJson = await client.GetStringAsync(Constants.SignalRNegotiateFunctionURL);
                    NegotiateInfo negotiate = JsonConvert.DeserializeObject<NegotiateInfo>(negotiateJson);
                    connection = new HubConnectionBuilder()
                        .WithUrl(negotiate.Url, options =>
                        {
                            options.AccessTokenProvider = async () => negotiate.AccessToken;
                        })
                        .ConfigureLogging( logging =>
                        {
                            // This will set ALL logging to Debug level
                            logging.SetMinimumLevel(LogLevel.Debug);
                        })
                        .Build();
                    connection.Closed += Connection_Closed;
                    connection.On<JObject>("OnAssetApproaching", OnAssetApproachingSignalREvent);
                }
                IsConnected = true;
                await connection.StartAsync();

            }
            catch (Exception ex)
            {
                IsConnected = false;
                //log exception here --->
            }
        }

由于某些原因,在没有收到来自服务器错误的任何消息的30秒后,我一直保持服务器超时。不知道为什么我的KeepAlive信号不是由Azure SignalR发送的。无论如何,因为我无法找到解决方法,所以请考虑像下面这样重新连接集线器。

async Task Connection_Closed(Exception arg)
{
   if(IsConnected)
   {
      // connected closed, try to reconnect.
      await TextToSpeech.SpeakAsync($"Realtime reconnecting. Reason: {arg.Message}.");
      await Task.Delay(15000);
      await ConnectAsync(AssetId);
    }
}

现在的问题是,等待connection.StartAsync();这次引发错误,提示无法发送请求或有时无法解析URL等。

有人可以告诉我我在做什么错吗?

是否有最佳实践或设计模式来管理此类问题。

0 个答案:

没有答案