Skip to content
Shiny PlatformShiny Platform

Connecting Clients

Register a client per contract, with the hub’s name and the transports it may use:

builder.Services.AddUniversalHubClient<IGameHub>("game", o => o
.UseHttp("_mygame._tcp", h => h.ConnectTimeout = TimeSpan.FromSeconds(4))
.UseMultipeer("mygame-mc")
.UseNearby("com.mycompany.mygame")
.UseBluetoothLE("180D", GameCharacteristicUuid)
.Priority<NearbyClientTransport, HttpClientTransport>()); // optional - the Use… order otherwise
  • The name and each transport’s settings match what the host gave the hub: the mDNS type, the Multipeer service type, the Nearby service id, the BLE service and characteristic.
  • Transports are tried in the order they’re added, unless Priority<…>() says otherwise (transports left out follow in the order they were added).
  • At least one transport. Each transport once per client. Mistakes throw at registration.
Option Default
UseBluetoothLE, UseHttp, UseMultipeer, UseNearby The transports: see Bluetooth LE, HTTP, Multipeer, Nearby
UseTransport(sp => ...) A transport of your own
Priority<T1, T2…>() the Use… order The order transports are tried in when a host is seen on several
Serializer(serializer) the app’s The hub’s own serializer, by name
Protocol(p => ...) HubProtocolOptions: payload size, RequestTimeout. App-wide
AutomaticReconnect true Resume after a dropped link instead of disconnecting

Resolve whichever shape you prefer. They are the same connection:

Inject You get
IUniversalHubClient<IGameHub> Discovery, connecting, transports, plus .Hub for calls and events (easiest to mock)
IHubProxy<IGameHub> The connection and .Hub, without discovery
IGameHub Calls and events only

DiscoverAll() watches for hosts over every transport at once. A host seen several ways is one HubHostInfo, raised again whenever any transport’s view changes. Dispose the subscription to stop.

public class JoinViewModel(IUniversalHubClient<IGameHub> client)
{
IDisposable Scan() => client
.DiscoverAll()
.Subscribe(host =>
{
// host.Key: stable across every transport
// host.Name, host.HostId
// host.Transports: the client transport types it is seen on, in priority order - empty means it has gone
var rssi = host.Endpoint<BleHubEndpoint>()?.Rssi;
var onWifi = host.IsSeenOver<HttpClientTransport>();
});
}
  • Merging. Results are merged by the host’s name, because a BLE advertisement has no room for a host id. Give hosts distinct names (UniversalServerOptions.LocalName).
  • Filtering. A host is listed when it runs your hub, where the transport can tell (mDNS, Multipeer and Nearby list their running hubs; a BLE scan only sees the service).
  • Missing transports. A transport that can’t scan (Bluetooth off, no Wi-Fi, not this platform) is skipped, and the others keep going. DiscoverAll([typeof(HttpClientTransport)]) browses only some.
  • Its own host. An app that hosts and scans at once doesn’t list itself.
await client.Connect(host, new HubConnectOptions("Allan", AppVersion: "1.2", Properties: new() { ["team"] = "blue" }));
await client.Hub.MakeMove(4);
// client.Transport is the IHubClientTransport carrying the connection, null while disconnected

Connect tries the transports the host is seen on, in priority order, falling back to the next when one fails. Per connect, HubConnectOptions can change the order:

new HubConnectOptions("Allan").Prefer<BleClientTransport>(); // tried first, then the rest
new HubConnectOptions("Allan").Allow<HttpClientTransport>().Allow<NearbyClientTransport>(); // only these
new HubConnectOptions("Allan").Only<NearbyClientTransport>(); // this and nothing else
  • Refusals aren’t retried. A host that refuses the client (full, ValidateClient, the hub isn’t running, a serializer mismatch) throws a HubException (“Host refused…”) and isn’t tried on another transport.
  • No migration. The transport is chosen at connect. A connection doesn’t move between transports mid-session.
Member
Status Disconnected, Connecting, Connected, Disconnecting, Reconnecting
StatusChanged / Connected / Disconnected Disconnected carries a HubDisconnect. StatusChanged carries it while Disconnecting, Disconnected and Reconnecting
HostName / HostRenamed The host’s name, kept up to date when the host renames itself
ClientName / Rename(name) The name the host knows you by. See Renaming
Transports / Transport Every transport this client has, and the one carrying the connection
CanTransferFiles, UploadFile, DownloadFile See Files
CanOpenMediaChannel, OpenMediaChannel See Media Channels
Disconnect() Leaves the hub, telling the host first

While the app runs, turn a client’s transports on and off, to test each on its own or to let the user pick:

await client.Disable<BleClientTransport>();
await client.Enable<BleClientTransport>();
await client.Solo<NearbyClientTransport>(); // this one on, every other off
bool on = client.IsEnabled<HttpClientTransport>();
client.EnabledChanged += (_, _) => Refresh();

A disabled transport leaves running discoveries (hosts it saw lose it) and is never connected over. Disabling the one a connection is on disconnects it.

A dropped link comes back as the same connection, on every transport: same connection id, groups and Properties, with the pushes it missed replayed. The host holds it for its resume window (30 seconds), and the client reconnects by itself on the transport it dropped from.

  1. Status goes to Reconnecting, and StatusChanged says why the link dropped.
  2. The client opens a new link (a new WebSocket, a new Multipeer session, a Nearby or BLE reconnect) and hands back its resume token.
  3. It is Connected again, and the pushes it missed are raised in order. Connected isn’t raised again.
client.StatusChanged += (_, e) => MainThread.BeginInvokeOnMainThread(() => this.Banner = e.Status switch
{
HubClientStatus.Reconnecting => $"Reconnecting over {client.Transport?.DisplayName}...",
HubClientStatus.Disconnected => $"Disconnected: {e.Reason}",
_ => null
});
  • Calls in flight when the link dropped, and calls made while Reconnecting, throw HubDisconnectedException.
  • Media channels and file transfers close. Open a new channel once Connected.
  • A drop that outlasts the window ends in Disconnected with ClientTimeout.
  • Turn it off with o.AutomaticReconnect = false. The host then lets the client go as soon as its link drops.
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 with no reply within HubProtocolOptions.RequestTimeout (30 seconds) throws a TimeoutException. Streams aren’t timed out. Set it with o.Protocol(p => p.RequestTimeout = ...).
  • Cancellation: cancelling a call’s CancellationToken stops waiting and cancels the hub method on the host.
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.

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));
};

ConnectionFailed is reported through StatusChanged only: Disconnected isn’t raised for a client that never connected. See Disconnect Reasons for the full table.

Exception When
HubRemoteException The hub method threw. Includes RemoteErrorType and Message
HubDisconnectedException You called while not connected (or Reconnecting), or the link dropped while a call was in flight. Disconnect says why
HubException The host refused the client at connect, or a transport failed
TimeoutException No reply within RequestTimeout
OperationCanceledException You cancelled the call

Register a client per hub. Each connects on its own; over BLE, clients connected to the same host share one BLE connection, which is reference counted, so disconnecting one leaves the others connected.

builder.Services.AddUniversalHubClient<IGameHub>("game", o => o.UseHttp("_mygame._tcp").UseBluetoothLE("FE10", GameCharacteristicUuid));
builder.Services.AddUniversalHubClient<IChatHub>("chat", o => o.UseHttp("_mygame._tcp").UseBluetoothLE("FE10", ChatCharacteristicUuid));

A BLE scan only sees the host’s service, not which hubs it is running. Joining a hub that’s stopped is refused at the handshake (HubException, “Host refused…”), so handle that.