Skip to content
Shiny.NET

Hosting Hubs

builder.Services.AddBleHubServer(server => server
.ServiceUuid(ServiceUuid) // optional - the one service every hub lives in; clients set the same
.Host(o => o.LocalName = "TTT") // advertised name - keep it short
.AddHub<GameHub>(GameHubCharacteristicUuid, o =>
{
o.MaxClients = 6; // default 8, null = unlimited
o.ValidateClient = info => String.IsNullOrWhiteSpace(info.Name) ? "A player name is required" : null;
})
.AddHub<ChatHub>(ChatHubCharacteristicUuid)
);
  • One call registers everything: every hub, the host settings (.Host(...), BleHubHostOptions) and the app-wide protocol limits (.Protocol(...)). Call AddBleHubServer once, with at least one hub. A hub or characteristic added twice, or a malformed UUID, throws at registration.

  • The platform BLE hosting stack is registered for you on Android, iOS and Mac Catalyst (AddBluetoothLeHosting()). On plain net10.0, register an IBleHostingManager yourself.

  • Every hub needs its own characteristic UUID. Use full 128-bit UUIDs.

  • Every hub lives in one service, set with server.ServiceUuid(...), and that is the only UUID the host advertises. Two 128-bit UUIDs don’t fit in a 31 byte advertisement, so hubs don’t get their own. The default (BleHubProtocolOptions.DefaultServiceUuid) is shared by every app using this library: set your own so other apps’ hosts stay out of your scans.

  • ValidateClient sees the client’s handshake (Name, AppVersion, Properties). Return a reason to refuse the client, or null to accept it.

public class GameHub(GameEngine engine) : BleHub<IGameHub>
{
public override async Task OnConnectedAsync()
=> await this.Groups.AddToGroupAsync(this.Context.ConnectionId, "lobby");
public override async Task OnDisconnectedAsync(HubDisconnect disconnect)
{
engine.Leave(this.Context.ConnectionId); // disconnect.Reason says why - see Disconnect Reasons below
await this.Clients.All.StateChanged(engine.Snapshot());
}
public async Task<MoveResult> MakeMove(int cell)
{
var error = engine.TryMove(this.Context.ConnectionId, cell);
if (error != null)
return new MoveResult(false, error);
await this.Clients.All.StateChanged(engine.Snapshot());
return new MoveResult(true, null);
}
// the contract's CancellationToken may be taken (as the last parameter) or left out
public async IAsyncEnumerable<int> Countdown(int from, [EnumeratorCancellation] CancellationToken ct)
{
for (var i = from; i > 0; i--)
{
yield return i;
await Task.Delay(1000, ct);
}
}
...
}
Member
ConnectionId The caller’s id
Client Name, AppVersion, Properties, Mtu (the ATT MTU of its BLE link, 0 on another transport), ConnectedAt, Items, and Peripheral: the BLE central (IPeripheral), null for a client connected over another transport
Items Per-connection state, kept while the client is connected
ConnectionAborted Cancelled when the client goes away
Abort(reason) Asks the client to leave. Called from a hub method, it takes effect after that method’s reply is sent
Target Who
All Everyone connected
Caller / Others The caller / everyone except the caller
Client(id) / Clients(ids) Specific connections
AllExcept(ids) Everyone but these
Group(name) / Groups(names) Group members
GroupExcept(name, ids) / OthersInGroup(name) Group members, minus some

Every target exposes the contract’s events as methods (Clients.Others.Emote("host", "👋")).

Groups.AddToGroupAsync(connectionId, name), RemoveFromGroupAsync, and GetMembers(name). When a client leaves, its memberships are removed automatically, after OnDisconnectedAsync has run.

OnDisconnectedAsync(HubDisconnect disconnect) tells you why a client left. disconnect.Reason is a HubDisconnectReason you can switch on, disconnect.Message is the optional text passed to Abort, Stop or Disconnect, and disconnect.Description is the message or a default text for the reason.

HubDisconnectReason When
ClientDisconnect The client called Disconnect() or was disposed. It tells the host before it unsubscribes
ClientTimeout The link dropped: an unsubscribe with no goodbye first (iOS and Android report a vanished client this way), or the cleanup sweep
ServerDisconnect Context.Abort(reason) or IHubContext.Disconnect(id, reason)
ServerShutdown IBleHubHost.Stop(reason) or IHubContext.Stop(reason)
public override Task OnDisconnectedAsync(HubDisconnect disconnect)
{
if (disconnect.Reason == HubDisconnectReason.ClientTimeout)
engine.HoldSeat(this.Context.ConnectionId); // the link dropped - they may come back
else
engine.Leave(this.Context.ConnectionId);
return Task.CompletedTask;
}

By default OnDisconnectedAsync(HubDisconnect) calls OnDisconnectedAsync(string? reason) with Description, so hubs that override the string version keep working. Override one or the other.

A connected client can change its name with client.Rename(name), without reconnecting. The host runs ValidateClient with the new name (and the client’s original AppVersion and Properties), then the hub’s OnRenamedAsync:

public override Task OnRenamedAsync(string? previousName)
{
if (engine.IsTaken(this.Context.Client.Name))
throw new InvalidOperationException("That name is taken"); // refused - the client keeps its old name
return this.Clients.Others.PlayerRenamed(previousName, this.Context.Client.Name);
}
  • Context.Client.Name already has the new name. Throwing puts the old one back, and the client gets a BleHubRemoteException (of type BleHubRemoteException.RenameRefused) with your message.
  • A client’s renames run one at a time.
  • Other clients aren’t told automatically. Push it yourself, as above, if they need to know.
  • IHubContext<THub>.ClientRenamed is raised after a rename is accepted, with BleHubClientRenamedEventArgs(Client, PreviousName).

An exception thrown by a hub method is sent back to the caller as a BleHubRemoteException (with RemoteErrorType and Message). The connection stays up.

RemoteErrorType is the exception’s class name, unless the hub throws a BleHubRemoteException itself: then the caller gets its RemoteErrorType, on every transport. That is how a hub relaying someone else’s error keeps that error’s type:

throw new BleHubRemoteException("GameRule", "Not your turn"); // the caller's RemoteErrorType is "GameRule"

BleHubRemoteException.TypeOf(exception) gives the type a caller is told, for transports of your own.

Inject IHubContext<THub> anywhere: services, view models, timers.

public class Lobby(IHubContext<GameHub> hub)
{
public Task Open() => hub.Start(); // start just this hub
public Task Close() => hub.Stop("The lobby is closed"); // clients get the reason
public bool IsOpen => hub.IsRunning;
public Task Broadcast(GameState state) => hub.Clients.All.StateChanged(state);
public Task Kick(string connectionId) => hub.Disconnect(connectionId, "Removed by host");
public IReadOnlyList<BleHubConnectedClient> Players => hub.ConnectedClients;
}

IHubContext<THub> also has Groups and the ClientConnected / ClientDisconnected / ClientRenamed events, plus MediaChannelOpened and GetMediaChannel(connectionId) for live packet streams. ClientDisconnected raises BleHubClientDisconnectedEventArgs(Client, Disconnect). e.Disconnect is the HubDisconnect, and e.Reason is its Description.

IBleHubHost.Start() / Stop(reason) Every registered hub
IHubContext<THub>.Start() / Stop(reason) Just that hub
IBleHubHost.Rename(localName) Changes the host’s name without stopping anything
  • Stopping a hub tells its clients to disconnect (they receive ServerShutdown and the reason) and refuses new clients with “Hub is not running”.
  • One service: every hub’s characteristic lives in one GATT service. It stays up while any hub is running, so stopping one hub never drops another hub’s clients.
  • Advertising starts with the first running hub and stops with the last. Starting or stopping a hub beside another doesn’t touch it.
  • Renaming the host: IBleHubHost.Rename("TTT 2") sets LocalName, re-advertises under the new name while hubs are running, and tells every connected client (their HostName updates and HostRenamed is raised). While stopped, it just sets the name the next Start uses.
  • Shared resources: BLE access, the file server and the cleanup sweep start with the first running hub and stop with the last.

A handler hub has no compiled hub class: its methods are dispatched by name to an IBleHubHandler, and values stay exactly as the caller’s IBleHubSerializer wrote them, so the host never needs their types. It is an advanced seam, hidden from IntelliSense, that Universal Hubs’ dynamic hubs are built on. Prefer those unless you’re writing a transport or host of your own.

  • Registration. AddBleHubServer(server => server.AllowHandlerHubs()) lets the server start with no compiled hubs.
  • IBleHubHandlerHost adds hubs while the app runs: Add(characteristicUuid, name, options, handler) returns an IBleHubHandle (Start, Stop, Clients, Groups, ConnectedClients, Disconnect, TransportEndpoint), and Remove(characteristicUuid, reason) stops and forgets one.
  • The one service. A hub added while the GATT service is up rebuilds it when it first starts, and the other hubs’ BLE clients are asked to reconnect then. A removed hub’s characteristic refuses handshakes until the next rebuild.
  • Serialized values. BleHubArgumentReader.ReadSerialized() reads an argument as the caller’s bytes, and BleHubArgumentWriter.WriteSerialized(bytes) adds one already serialized: push.Send(name, push.CreateArguments().WriteSerialized(value)).