SignalR Client Setup
dotnet add package Microsoft.AspNetCore.SignalR.Client
public class ChatService
{
HubConnection? _hub;
public async Task ConnectAsync(string token)
{
_hub = new HubConnectionBuilder()
.WithUrl("https://api.example.com/chathub", opts =>
opts.AccessTokenProvider = () => Task.FromResult(token)!)
.WithAutomaticReconnect()
.Build();
// Subscribe to server-pushed messages
_hub.On<string, string>("ReceiveMessage", (user, msg) =>
MainThread.BeginInvokeOnMainThread(() =>
Messages.Add(new ChatMessage(user, msg))));
await _hub.StartAsync();
}
public async Task SendAsync(string msg) =>
await _hub!.SendAsync("SendMessage", msg);
public async Task DisconnectAsync() =>
await _hub!.StopAsync();
}
💡WithAutomaticReconnect() handles network drops with exponential backoff — no manual reconnection logic needed.
Key Takeaways
Microsoft.AspNetCore.SignalR.Client works on Android via MAUI
Hub.On() subscribes to server-pushed events
Always update UI on the main thread with MainThread.BeginInvokeOnMainThread
WithAutomaticReconnect() retries after network drops automatically