Hosting
The Universal Server
Section titled “The Universal Server”One call registers the server, every hub it serves and the transports each hub is served over:
builder.Services.AddUniversalServer(server => server .Configure(o => { o.LocalName = "Allan's iPad"; // advertised by every transport that advertises o.EnableFileTransfers(filesDir, ft => ft.MaxUploadSize = 25 * 1024 * 1024); o.AuthorizeFile = req => req.FileName.StartsWith("avatar-"); o.EnableMediaChannels(); }) .Multipeer("mygame-mc") // transport-wide settings, where a transport has them .Nearby("com.mycompany.mygame") .AddHub<GameHub>("game", hub => hub .MaxClients(6) // counted across every transport .ValidateClient(info => String.IsNullOrWhiteSpace(info.Name) ? "A player name is required" : null) .UseHttp("_mygame._tcp") .UseMultipeer() .UseNearby() .UseBluetoothLE(serviceUuid: "180D", characteristicUuid: GameCharacteristicUuid)) .AddHub<ChatHub>("chat", hub => hub.UseHttp("_mychat._tcp", allowTunnel: true)));| Server builder | What it sets |
|---|---|
Configure(o => ...) |
UniversalServerOptions, shared by every hub and transport (below) |
Protocol(o => ...) |
HubProtocolOptions: payload size, timeouts. App-wide, so a client in the same app gets them too |
AddHub<THub>(name, hub => ...) |
One hub, its rules and its transports |
AllowDynamicHubs(o => ...) |
Dynamic hubs |
BluetoothLE(o => ...), Http(o => ...), HttpServer(http => ...), Multipeer(type), Nearby(id) |
Transport-wide settings: see Bluetooth LE, HTTP, Multipeer, Nearby |
AddTransport<T>() |
A transport of your own, for a server with only dynamic hubs |
| Hub builder | |
|---|---|
UseBluetoothLE(service, characteristic, advertise), UseHttp(type, allowTunnel), UseMultipeer(), UseNearby() |
The transports it is served over. At least one |
UseTransport<T>(settings) |
A transport of your own |
MaxClients(n) |
The most clients at once, across every transport. 8 unless set, null for no limit |
ValidateClient(info => ...) |
Sees the client’s handshake (Name, AppVersion, Properties). Return a reason to refuse, or null to accept. It also sees a rename |
Serializer(serializer) |
This hub’s own serializer |
- A hub’s name is how clients ask for it on every transport: 1 to 64 letters, digits,
.,_and-, starting with a letter or digit. Clients register the same name. - Registration mistakes throw at registration:
AddUniversalServercalled twice, no hubs, a hub with no transport, a duplicate hub or name, the same transport twice on a hub, a transport set up that no hub uses, two hubs on one BLE characteristic, and BLE services that don’t fit in the advertisement. - Nothing starts on its own.
IUniversalHubHoststarts and stops the hubs.
UniversalServerOptions
Section titled “UniversalServerOptions”| Option | Default | |
|---|---|---|
LocalName |
null |
The host’s name, sent in every handshake and advertised. Keep it short over BLE |
HostId |
a new id each app start | Identifies the host across transports, so a client that sees it several ways shows it once. Persist one for a stable id |
ResumeWindow |
30 seconds | How long a dropped client is held. Zero turns it off |
ResumeBufferSize |
128 | Pushes kept for a held client |
EnableFileTransfers(dir, ft => ...) |
off | File transfers on every transport |
AuthorizeFile |
null |
A gate for file transfers on every transport. Return false to refuse |
EnableMediaChannels(maxPacketSize) |
off | Media channels on every transport |
Writing a Hub
Section titled “Writing a Hub”public class GameHub(GameEngine engine) : UniversalHub<IGameHub>{ public override async Task OnConnectedAsync(HubConnection connection) => await this.Groups.AddToGroupAsync(connection.Id, "lobby");
public override async Task OnDisconnectedAsync(HubConnection connection, HubDisconnect disconnect) { engine.Leave(connection.Id); // 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); } } ...}The Connection
Section titled “The Connection”OnConnectedAsync, OnDisconnectedAsync and this.Connection give a HubConnection: one id on every transport, and
the transport the client is on.
public override Task OnConnectedAsync(HubConnection connection){ // connection.Id: the central's id over BLE, ws:{id} over HTTP, mc:{id} over Multipeer, nb:{id} over Nearby // connection.Client: name, app version, handshake properties // connection.Properties: your own state for the connection - the same bag on every transport
if (connection.Transport is BleHostTransport) engine.MarkSlowLink(connection.Id);
var user = connection.HttpContext()?.User; // HTTP: the WebSocket's request var central = connection.Peripheral(); // BLE: the central (IPeripheral) var mc = connection.MultipeerPeer()?.DisplayName; // Multipeer var nb = connection.NearbyPeer()?.EndpointName; // Nearby return Task.CompletedTask;}Each extension comes from its transport’s package and is null on the others. connection.Get<T>() reads any feature
a transport offers, by type.
Context
Section titled “Context”| Member | |
|---|---|
ConnectionId |
The caller’s id |
Client |
Name, AppVersion, Properties, Mtu (the ATT MTU over BLE, 0 elsewhere), ConnectedAt, Items, and Get<T>() for transport features |
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 |
Clients
Section titled “Clients”| Target | Who |
|---|---|
All |
Everyone connected, on every transport |
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
Section titled “Groups”Groups.AddToGroupAsync(connectionId, name), RemoveFromGroupAsync, and GetMembers(name). Groups span every
transport. When a client leaves, its memberships are removed after OnDisconnectedAsync has run.
Renaming
Section titled “Renaming”A connected client can change its name with client.Rename(name), without reconnecting. The host runs ValidateClient
with the new name, 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.Namealready has the new name. Throwing puts the old one back, and the client gets aHubRemoteExceptionof typeHubRemoteException.RenameRefusedwith your message.- Other clients aren’t told automatically. Push it yourself if they need to know.
IHubContext<THub>.ClientRenamedis raised after a rename is accepted.IUniversalHubHost.Rename(localName)renames the host on every transport without stopping anything. Connected clients getHostRenamed.
Errors
Section titled “Errors”An exception thrown by a hub method reaches the caller as a HubRemoteException (with RemoteErrorType and
Message). The connection stays up.
RemoteErrorType is the exception’s class name, unless the hub throws a HubRemoteException itself. Then the caller
gets its RemoteErrorType, so a hub relaying someone else’s error keeps that error’s type:
throw new HubRemoteException("GameRule", "Not your turn"); // the caller's RemoteErrorType is "GameRule"HubRemoteException.TypeOf(exception) gives the type a caller is told, for transports of your own.
Outside a Hub: IHubContext
Section titled “Outside a Hub: IHubContext”Inject IHubContext<THub> anywhere: services, view models, timers.
public class Lobby(IHubContext<GameHub> hub){ public Task Open() => hub.Start(); // just this hub, on all its transports 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<HubConnectedClient> Players => hub.ConnectedClients;}IHubContext<THub> also has Groups, the ClientConnected / ClientDisconnected / ClientRenamed events, and
MediaChannelOpened / GetMediaChannel(connectionId). ClientDisconnected
raises HubClientDisconnectedEventArgs(Client, Disconnect).
Starting and Stopping
Section titled “Starting and Stopping”IUniversalHubHost starts and stops every hub, one hub, one transport, or one hub on one transport:
await host.Start(); // every hub on every transport it pickedawait host.Stop("The host closed the app");
await host.StartHub<ChatHub>(); // one hub, left runningawait host.StopHub<GameHub>("Game over"); // its clients get ServerShutdown; the chat carries on
await host.Stop<BleHostTransport>(); // one transport off; the others keep their clientsawait host.Start<BleHostTransport>();await host.StartHub<GameHub, NearbyHostTransport>(); // one hub on one transportawait host.StopHub<GameHub, NearbyHostTransport>();- A transport that can’t start (Bluetooth off, no network, not this platform) is skipped as long as another starts.
Startreturns the transports that did, and throws when none could. - What’s running:
Transports,RunningTransports,GetRunningTransports<THub>(),host.IsRunning<T>(),host.GetTransport<T>()and theRunningChangedevent.ListenUrlshas the HTTP server’s addresses. - Stopping tells connected clients why, with
ServerShutdown, and refuses new clients. - Files:
FileTransferredandFileTransferProgressare raised for transfers on every transport.
Dropped Links & Resume
Section titled “Dropped Links & Resume”A client whose link drops (out of range, its app went to the background) is held rather than let go. If it comes back in time it is the same connection, and the hub never sees it leave:
server.Configure(o =>{ o.ResumeWindow = TimeSpan.FromSeconds(60); // default 30s; TimeSpan.Zero turns holding off o.ResumeBufferSize = 128; // pushes kept for a held client (the default)});- What’s held: the client stays in
ConnectedClients, its groups and theMaxClientscount, and keeps its connection id andItems. Pushes to it are kept, in order. - When it comes back: it hands back a secret resume token from its handshake on a new link, on the transport it dropped from, carries on as the same connection, and the kept pushes are replayed before anything new.
- When it doesn’t:
OnDisconnectedAsyncruns withClientTimeoutonce the window runs out, or as soon as more is pushed to it thanResumeBufferSizekeeps. - Never held: a client that says goodbye,
Context.Abort/IHubContext.DisconnectandStop. Stopping lets held clients go straight away. - Lost in the drop: hub methods running when the link dropped are cancelled (the client has failed those calls), and media channels and file transfers close.
Disconnect Reasons
Section titled “Disconnect Reasons”Every disconnect carries a HubDisconnect: a HubDisconnectReason you can switch on, and an optional Message
(Description is the message or a default text). It means the same on every transport, and the host and the client see
the same value.
| Reason | When |
|---|---|
ClientDisconnect |
The client called Disconnect() or was disposed. It says goodbye first |
ClientTimeout |
The link dropped without a goodbye and the resume window ran out (or the client can’t resume) |
ServerDisconnect |
Context.Abort(reason) or IHubContext.Disconnect(id, reason) |
ServerShutdown |
IUniversalHubHost.Stop, StopHub, IHubContext.Stop, or the client’s transport stopped |
ConnectionFailed |
The connect or handshake failed (client side) |
public override Task OnDisconnectedAsync(HubConnection connection, HubDisconnect disconnect){ if (disconnect.Reason == HubDisconnectReason.ClientTimeout) engine.MarkAway(connection.Id); // dropped and didn't come back within the resume window else engine.Leave(connection.Id); return Task.CompletedTask;}
