Connecting Clients
Registration
Section titled “Registration”builder.Services.AddBleHubClient<IGameHub>(GameHubCharacteristicUuid, o => o.ServiceUuid = ServiceUuid); // optional - must match the hostThe client scans for and connects to BleHubClientOptions.ServiceUuid, the one service every hub lives in (see
How It Works). Set the same UUID the host uses; both default to
BleHubProtocolOptions.DefaultServiceUuid.
On Android, iOS and Mac Catalyst the platform BLE stack is registered for you (AddBluetoothLE()). On Apple it turns
off iOS’s background alerts (connect, disconnect and notification alerts while the app isn’t in the foreground),
because hubs are used in the foreground. To use your own AppleBleConfiguration, call AddBluetoothLE(config) before
AddBleHubClient: the first registration wins. On plain net10.0, register an IBleManager yourself.
This registers the generated proxy (GameHubClient for IGameHub) as a singleton. Inject whichever shape you
prefer:
| Inject | You get |
|---|---|
IBleHubClient<IGameHub> |
Connection management, plus .Hub for calls and events (easiest to mock) |
GameHubClient |
The concrete generated proxy |
IGameHub |
Calls and events only |
Discover & Connect
Section titled “Discover & Connect”public partial class JoinViewModel(IBleHubClient<IGameHub> client) : ObservableObject{ IDisposable? scan; public ObservableCollection<BleHubHostInfo> Hosts { get; } = new();
public void OnAppearing() => this.scan = client .Discover() // scans for the service UUID - dispose to stop .Subscribe(host => MainThread.BeginInvokeOnMainThread(() => { if (!this.Hosts.Any(x => x.Id == host.Id)) this.Hosts.Add(host); // host.Name (advertised), host.Rssi }));
[RelayCommand] async Task Join(BleHubHostInfo host) { this.scan?.Dispose(); await client.Connect(host, new BleHubConnectOptions( Name: "Allan", AppVersion: AppInfo.Current.VersionString, Properties: new() { ["team"] = "blue" } )); var result = await client.Hub.Join("Allan", null); }}Discover leaves out the app’s own host. An app that hosts hubs and scans at the same time (both roles on one
device) would otherwise list itself, because a scan can report the device’s own advertisement. The match is the
service UUID plus the advertised local name, since the advertisement has no room for anything else. That means:
- give hosts distinct names: another host with the same name is hidden while this app advertises
- an advertisement with no name is always listed
Connect does the following:
- Connects to the host.
- Asks for the largest ATT MTU, 517. Android negotiates it; Apple platforms negotiate on their own and can’t be asked.
- Subscribes for pushes.
- Completes the handshake.
The host may refuse the client: it is full, ValidateClient said no, or the hub isn’t running. In that case
Connect throws a BleHubException with the reason.
| Member | |
|---|---|
Status |
Disconnected, Connecting, Connected, Disconnecting |
StatusChanged / Connected / Disconnected |
Disconnected carries a HubDisconnect saying why. StatusChanged carries it as Disconnect while Disconnecting and Disconnected |
Host / HostName |
The connected host, and its name: from the handshake, kept up to date when the host renames |
ClientName |
The name the host knows you by: BleHubConnectOptions.Name, or your latest Rename. null while disconnected |
CanTransferFiles |
See File Transfers |
Disconnect() |
Leaves the hub, telling the host first |
Rename(name) / HostRenamed |
See Renaming |
Renaming
Section titled “Renaming”Change the name the host knows you by without reconnecting:
try{ await client.Rename("Allan B");}catch (BleHubRemoteException ex) when (ex.RemoteErrorType == BleHubRemoteException.RenameRefused){ this.Show(ex.Message); // the host said no - client.ClientName is unchanged}- The host checks the new name with
ValidateClient, then runs the hub’sOnRenamedAsync. Either can refuse. - Renaming to the current name does nothing. Renaming while disconnected throws
BleHubDisconnectedException. - A later
Connectuses the name in its ownBleHubConnectOptions. - A host older than renames refuses with a
BleHubRemoteExceptiontoo.
When the host renames itself, HostRenamed is raised with the new name. HostName is already updated, and the event
arrives in order with the hub’s events, on the same background thread.
client.HostRenamed += (_, name) => MainThread.BeginInvokeOnMainThread(() => this.Title = name);Disconnect Reasons
Section titled “Disconnect Reasons”Disconnected is an EventHandler<HubDisconnect>. Reason is a HubDisconnectReason you can switch on, Message is
the host’s text (from Abort, Stop or Disconnect) if it gave one, and Description is the message or a default
text for the reason.
client.Disconnected += (_, disconnect) =>{ var text = disconnect.Reason switch { HubDisconnectReason.ServerShutdown => "The host closed the game", HubDisconnectReason.ServerDisconnect => disconnect.Message ?? "You were removed from the game", HubDisconnectReason.ClientTimeout => "Lost the connection to the host", _ => null // ClientDisconnect - we left }; if (text != null) MainThread.BeginInvokeOnMainThread(() => this.Show(text));};HubDisconnectReason |
When |
|---|---|
ClientDisconnect |
You called Disconnect() or disposed the client |
ClientTimeout |
The link to the host dropped |
ServerDisconnect |
The host disconnected this client (Context.Abort or IHubContext.Disconnect). A disconnect from an older host that doesn’t send a reason also arrives as this |
ServerShutdown |
The host stopped the hub, or stopped hosting |
ConnectionFailed |
Connect or the handshake failed. Disconnected isn’t raised, because the client never connected. StatusChanged still reports it |
var result = await client.Hub.MakeMove(4);await client.Hub.Rematch();
using var cts = new CancellationTokenSource();await foreach (var n in client.Hub.Countdown(10, cts.Token)){ if (n == 3) break; // cancels the hub method on the host}- Concurrent calls are fine. Each is matched to its own reply.
- Timeouts: a call that gets no reply within
BleHubProtocolOptions.RequestTimeout(30s by default) throws aTimeoutException. Streams aren’t timed out. - Cancellation: cancelling a call’s
CancellationTokenstops waiting and cancels the hub method on the host.
// protocol limits are app-wide - set them on any client registration (or the server's .Protocol)builder.Services.AddBleHubClient<IGameHub>(GameHubCharacteristicUuid, o => o.Protocol(p => p.RequestTimeout = TimeSpan.FromSeconds(10)));Events (pushes)
Section titled “Events (pushes)”client.Hub.StateChanged += state => MainThread.BeginInvokeOnMainThread(() => this.Apply(state));client.Hub.Emote += (from, emoji) => MainThread.BeginInvokeOnMainThread(() => this.Show($"{from} {emoji}"));Events are raised on a background thread, one at a time and in the order the host sent them. Marshal to the UI thread yourself.
Failures
Section titled “Failures”| Exception | When |
|---|---|
BleHubRemoteException |
The hub method threw. Includes RemoteErrorType and Message |
BleHubDisconnectedException |
You called while not connected, or the connection dropped while a call was in flight (Disconnect says why, and Reason is its text) |
TimeoutException |
No reply within RequestTimeout |
OperationCanceledException |
You cancelled the call |
Media Channels
Section titled “Media Channels”For live audio, video or any stream of binary packets, open the connection’s media channel when the host serves them:
if (client.CanOpenMediaChannel){ var media = await client.OpenMediaChannel(); // an ordered packet pipe beside the hub await media.Send(packet);}See Media Channels.
Several Hubs on One Host
Section titled “Several Hubs on One Host”Register a client per hub contract. Connecting each to the same host shares one BLE connection, which is reference counted, so disconnecting one hub client leaves the others connected.
builder.Services.AddBleHubClient<IGameHub>(GameHubCharacteristicUuid, o => o.ServiceUuid = ServiceUuid);builder.Services.AddBleHubClient<IChatHub>(ChatHubCharacteristicUuid, o => o.ServiceUuid = ServiceUuid);A scan only sees the host’s service UUID, not which hubs it is running. If a host runs a hub only on demand, joining
it while it is stopped is refused by the handshake (BleHubException, “Host refused…”), so handle that.


