【发布时间】:2019-12-07 01:48:43
【问题描述】:
我正在使用 Signalr 服务实现聊天的 Xamarin Forms 应用程序。聊天在 UWP 版本和 Android 模拟器中完美运行,所以当我在我的手机 (Android) 上进行调试时它确实如此,但是当我断开手机与 PC 的连接时,混乱开始了。问题是我认为当应用程序进入后台时,它会与 Signalr 服务器断开连接。
我已经尝试过自动重新连接,甚至更改了 ServerTimeout 和 KeepAliveInterval 的时间。但我一直没有成功。应该注意的是,我居住的地方还存在严重的连接问题,但我的理论仍然是应用程序进入后台时。
这是我初始化服务的代码(我使用的是单例服务)。
hubConnection = new HubConnectionBuilder()
.WithUrl(URL, options =>
{
options.AccessTokenProvider = () => Task.FromResult(_myAccessToken);
})
.WithAutomaticReconnect()
//.WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
//.WithAutomaticReconnect(new RandomRetryPolicy())
.Build();
这是我在连接关闭时连接的代码
hubConnection.Closed += async (error) =>
{
OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...",
string.Empty));
IsConnected = false;
await Task.Delay(new Random().Next(0, 5) * 1000);
try { await ReConnectAsync(); } catch (Exception ex) { Debug.WriteLine(ex); }
};
这是我的连接代码
public async Task ReConnectAsync()
{
await ConnectAsync();
}
public async Task ConnectAsync()
{
if (IsConnected)
{
return;
}
Debug.WriteLine(hubConnection.State);
if (hubConnection.State== HubConnectionState.Disconnected)
{
await hubConnection.StartAsync();
//CancellationToken cancellationToken = new CancellationToken();
//await ConnectWithRetryAsync(hubConnection, cancellationToken);
}
IsConnected = true;
}
我还能尝试什么来阻止它在 Android 上断开连接,或者我的代码会做错什么?
【问题讨论】:
标签: android xamarin xamarin.forms signalr signalr-hub