我在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等。
有人可以告诉我我在做什么错吗?
是否有最佳实践或设计模式来管理此类问题。