我在我的 Xamarin Forms 應用程式中實作了 SignalR,但出現連接超時錯誤。
我在應用程式中將 SignalR 用于兩件事。第一個是典型的聊天功能,第二個是通知用戶其他用戶與當前用戶互動觸發的后端重要資料更改。
我在一個服務類中實作了所有與 SignalR 相關的方法——見下文:
public class MySignalRService : IMySignalRService
{
private readonly url = "https://example.com/myhub";
HubConnection _connection;
public async Task Connect()
{
var accessToken = SecureStorage.GetAsync("access_token").Result;
_connection = new HubConnectionBuilder()
.WithUrl(_url, options =>
{
options.AccessTokenProvider = () => Task.FromResult(accessToken);
})
.Build();
await _connection.StartAsync();
_connection.On<string>("ReceiveMessage", async (message) =>
{
await UpdateChat(message);
});
_connection.On<string>("ReceiveDataUpdate", async (data) =>
{
await UpdateUserData(data);
});
}
private async Task UpdateChat(message)
{
// Handle message
}
private async Task UpdateUserData(data)
{
// Handle data update
}
public async Task Disconnect()
{
await _connection.DisposeAsync();
}
}
然后我在 for 的代碼中呼叫Connect()方法OnStart()和方法。我也在方法中呼叫方法。OnResume()App.xamlDisconnect()OnSleep()
我的想法是在我的應用程式在用戶設備上處于活動狀態時保持連接打開,但這仍然意味著一段時間不活動。
我有兩個問題:
- 我明白
SignalR不想坐以待斃。當用戶需要該功能并在完成后立即斷開連接時,是否SignalR可以完全連接到集線器?如果是這樣,我如何讓用戶知道更新?我是否要設定某種型別的長輪詢自己來經常醒來,SignalR這似乎違背了首先使用它的想法? - 如果那些
SignalR在 Xamarin Forms 中實作的人會讓我知道我采用的服務方法是否不是我需要在我的應用程式中實作它的方式,我也將不勝感激。
uj5u.com熱心網友回復:
請考慮幫助您了解開始故障排除/隔離問題的建議,有三種型別的斷開連接。
理解connection,生命周期和disconnections在以下情況下將縮小您的問題,至少斷開連接發生在哪里。
Transport disconnectionClient disconnectionServer disconnection
選項1:AutomaticReconnect
_yourHubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri($"/{HubMethods.SomeResultHub.my}"))
.WithAutomaticReconnect() // did you try this option
.Build();
_yourHubConnection.ServerTimeout = TimeSpan.FromHours(8); // Hrs 24/8 etc

根據 Microsoft 參考,使用代碼找出斷開連接的原因:
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
if (stopCalled)
{
Console.WriteLine(String.Format("Client {0} explicitly closed the connection.", Context.ConnectionId));
}
else
{
Console.WriteLine(String.Format("Client {0} timed out .", Context.ConnectionId));
}
return base.OnDisconnected(stopCalled);
}
擁有這兩個
你的問題 1/答案
...如果是這樣,我如何讓用戶知道更新?
$.connection.hub.reconnecting(function() {
notifyUserOfTryingToReconnect(); // wire up your custom function to notify user.
});
$.connection.hub.connectionSlow(function() {
notifyUserOfConnectionProblem(); // wire up your custom function let them know its slow.
});
問題 2:在 Xamarin / Android 上
在移動設備/Android 上(雖然 ios 很痛苦),您需要運行前臺服務,這有助于應用程式保持連接活動。或者,就像您最初的想法一樣,長輪詢是另一個不錯的選擇。
例如
[Service]
public class MyUserChatForegroundService : Service
{
// implement your foreground service to keep the connection alive.
...
}
無論您在何處使用 Intent 開始您的活動,都將其連接起來,最后是您的服務,
invoke StartForegroundusing OnStartCommand override,否則服務將被殺死。
var intent = new Intent(this, typeof(MyUserChatForegroundService ));
StartForegroundService(intent);

希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487702.html
標籤:xamarin xamarin.forms 信号器 信号器客户端 asp.net-core-signalr
