Session
TGorillaArenaSession is a group of devices that found each other, know who is
there, and can send each other messages. Drop it on a form, call OpenSession
on one device and JoinSession on the others — discovery, pairing, connecting
the profiles, the member list and one message channel are all done for you.
Turn taking is not in here; that is Match, which descends from this class.
Table of Contents
- Opening and Joining
- Roles
- Members
- Messages
- Choosing the Transport
- Users, Items and Entities
- Configuration
- Events
- Extension Points
- What the Session Repairs
- Linux
- Diagnostics
- See Also
Opening and Joining
FSession := TGorillaArenaSession.Create(Self);
FSession.MessageResource := 'MyGame';
FSession.AppVersion := 1;
FSession.OpenSession('Anna'); // one device
FSession.JoinSession('Ben'); // the others
FSession.JoinSession('Ben', '192.168.1.14'); // ... when discovery is blocked
FSession.CloseSession();
OpenSession reports the address it is reachable at through OnNotice —
worth showing, because it is what somebody types in when the automatic search
comes up empty. LocalAddress() returns the same value.
On Android both calls first ask for the Bluetooth permission and only then do
their work, so do not assume the session is up when the call returns. Wait
for OnMembersChanged or OnNotice.
The third form of JoinSession takes a host directly — an address or a manager
name. It is the way out on networks that isolate their clients from each other,
such as guest Wi-Fi with AP isolation. The Lobby Directory
exists so that players do not have to type it.
Roles
| Value | |
|---|---|
asrOffline |
Not in a session at all |
asrHost |
Opened the session; keeps the state and decides everything |
asrClient |
Joined somebody else's session |
Role, and the shortcuts IsHost and IsOffline, tell you where you stand.
Members
Members() returns everybody the session knows about, yourself included:
type
TGorillaArenaMember = record
Id : String; // stable identity, handed out by the session
Name : String; // what the others read
Here : Boolean; // false once somebody left mid match
end;
MyId() is your own id — empty until you opened or joined. MemberName(AId)
resolves an id, MemberCount counts them. OnMembersChanged fires whenever
the list moves.
Messages
One channel carries everything, named by MessageResource. Every message is a
JSON envelope with a version, a type, its sender, a sequence number and a free
form payload:
LMsg := FSession.NewMessage('chat');
LMsg.SetStr('text', 'well played');
FSession.SendMessage(LMsg); // takes ownership
Anything the framework does not recognise arrives at OnAppMessage:
procedure TForm1.AppMessage(const ASender : TObject;
AMessage : TGorillaArenaMessage; var AHandled : Boolean);
begin
if AMessage.MsgType = 'chat' then
begin
Memo1.Lines.Add(FSession.MemberName(AMessage.From) + ': '
+ AMessage.GetStr('text'));
AHandled := true;
end;
end;
The message is borrowed — it is freed as soon as the handler returns.
Two things are filtered out before any of that: your own broadcast coming back to you, and anything the sequence gate has already seen. Tethering does not promise ordering across resources and may deliver a resource twice, so every sender numbers its own messages upwards and anything not newer is dropped.
Choosing the Transport
Exactly one transport at a time:
| Value | Carried by | Platforms |
|---|---|---|
atNetwork |
App Tethering, UDP broadcast over the local network | Windows, Android, macOS, iOS |
atBluetooth |
App Tethering, RFCOMM to a device already paired at operating system level | Windows, Android, macOS |
atDirect (default) |
The Arena's own transport (Gorilla.Arena.Net): UDP discovery, one TCP connection per client to the host |
Windows x86/x64/ARM64EC, Linux x64, Android 32/64, macOS x64/ARM64 |
The two worlds do not see each other. A device on atDirect neither finds
nor is found by one on tethering. As soon as one participant runs Linux — where
atDirect is the only transport and is used whatever Transport says — every
device has to be set to atDirect.
FMatch.Transport := TGorillaArenaTransport.atDirect;
FMatch.OpenSession('Anna'); // host
FMatch.JoinSession('Ben'); // first host of this app that answers
FMatch.JoinSession('Ben', '192.168.1.14'); // that machine, no discovery
FMatch.JoinSession('Ben', 'box.local:47812'); // host name with port
FMatch.JoinSession('Ben', 'Anna'); // the host called Anna
How atDirect works
- A star. The host listens on TCP
DirectPort(47810 — when it is taken, the next nine are tried) and answers discovery on UDPDiscoveryPort(47811). Every client holds exactly one connection, to the host, which relays what a client sends to everybody else. The member list is the host's roster. - Discovery goes out as the limited broadcast and as the directed
broadcast of every local subnet, so a host behind the second network card is
found too. The host answers unicast and the client connects to the address
the answer came from — no
MULTIHOMEDproblem, nothing to choose by hand. - Keeping applications apart.
MessageResourceis the application key: a host ignores discovery requests of other applications and refuses their connections with a notice saying why. - Liveness. Idle connections ping every two seconds; ten seconds of silence end them. A client that closes says goodbye, so the host does not wait for the timeout.
- Threads. The host runs an Indy thread per client, a client one thread of
its own. Every event reaches the session on the main thread. A console
application has to call
CheckSynchronize. - Firewall. The host needs TCP
DirectPort(+9) and UDPDiscoveryPortopen inbound. Windows asks the first time a host opens. - Android takes the same multicast lock as tethering; it also lets broadcasts through the Wi-Fi power save filter.
Tethering: one adapter at a time
For atNetwork and atBluetooth this is a choice and not a set, and the
reason is structural: every allowed
adapter runs a discovery of its own, so both devices find each other more than
once and start a profile connection per find — and then sit in
TTetheringAppProfile.Connect waiting for an answer the other one cannot give,
because it is waiting itself. On Android the system kills the app for not
responding.
Bluetooth is the way out when the network is not one: a guest Wi-Fi that isolates its clients, a firewall in the way, or no Wi-Fi at all. It only ever reaches devices already paired at operating system level, and its search costs seconds per paired device.
Transport is read when a session is opened or joined, so changing it while
one is running does nothing until the next one.
Users, Items and Entities
Users, Items, Myself, OnUserEvent and OnItemEvent come from
TGorillaArenaCustomManager (Gorilla.Arena.Base) and are the same on every
platform and every transport.
// Myself exists once a session is open, and is shared by itself
FMatch.Myself.Position := Point3D(1, 0, 2); // everybody sees it
// several changes, one message
FMatch.Myself.BeginUpdate();
try
FMatch.Myself.Position := LPos;
FMatch.Myself.Color := LColor;
finally
FMatch.Myself.EndUpdate();
end;
// items of your own
TGorillaArenaEntity.RegisterEntityClass(TSword); // once, on every device
LSword := TSword.Create(FMatch);
LSword.Id := 'Excalibur';
LSword.Power := 5;
FMatch.AddItem(LSword); // everybody gets a TSword with Power = 5
LSword.Power := 7; // ... and this change
FMatch.RemoveItem(LSword); // ... and this
On atDirect:
| Rule | |
|---|---|
| Ownership | Whoever creates an entity owns it — its SourceProfile is the owner's member id. Only the owner sends it; a copy changed elsewhere stays local, and an entity claimed by somebody else is dropped |
| Changes | Every property change is sent as the whole entity; BeginUpdate/EndUpdate collapse a batch into one message |
| Late arrivals | Get the current state of every entity from every owner |
| Leaving | Takes the entities along — the others see Remove for that participant's user and items |
| Classes | Found by QualifiedName. Register your own with TGorillaArenaEntity.RegisterEntityClass on every device; an unknown class arrives as a plain TGorillaArenaEntity and says so in the log |
| Scope | Entities belong to the session: closing it clears Users and Items. Add items after OpenSession/JoinSession |
On tethering the entities keep doing what they always did — shared resources
and Item/Update streams through the app profile.
Configuration
| Property | Default | |
|---|---|---|
MessageResource |
ArenaMessage |
Name of the channel. Both sides need the same one — give each application its own |
AppVersion |
1 |
Version of your payloads. Two devices with different versions refuse to talk and say so |
EnvPrefix |
ARENA |
Prefix of the environment variables below |
LogTag |
Arena |
What platform log lines are prefixed with |
Transport |
atDirect |
See above. Was atNetwork before Linux support — an application that relied on that default and wants tethering has to set it now |
SearchInterval |
4000 |
Milliseconds between two searches |
SearchWindow |
3000 |
How long one search listens |
SearchMaxTries |
15 |
How many searches before giving up |
DirectPort |
47810 |
atDirect: TCP port of the host. The next nine are tried when it is taken |
DiscoveryPort |
47811 |
atDirect: UDP port of the discovery. The same on every device |
Events
| Event | |
|---|---|
OnNotice |
Something worth telling the user, in plain text |
OnMembersChanged |
Somebody arrived or left |
OnAppMessage |
A message no layer of the framework knew what to do with |
OnStatusChanged |
Pending when a session starts, Joined once it is up, None when it closes |
OnUserEvent |
A user was added, changed or removed |
OnItemEvent |
An item was added, changed or removed — ours or somebody else's |
The manager's own OnStatusChanged, OnUserEvent, OnMessage and OnError
stay free for you: the session overrides the protected DoStatusChanged,
DoUserEvent and DoErrorMessage methods instead of hooking its own events.
Extension Points
Override these in a descendant; each one is called with the member list already up to date.
| Method | |
|---|---|
DoSessionStarting |
A role was just taken, before the network comes up — throw away what the last session left behind |
DoSessionReady |
The session is up, with or without anybody else |
DoMemberArrived |
Somebody joined |
DoMemberGone |
Somebody left |
DispatchMessage |
Act on a message; return False for one you do not know |
Transmit |
The only place the session touches the network — override it to test the layers above without one |
RebuildMembers |
Rebuild the member list; likewise a test seam |
Note when overriding
DoStatusChangedorDoUserEventyourself: checkFDestroyingand leave at once when it is set. The manager reports its own teardown through them, and by then nothing may act any more.
What the Session Repairs
Five things that are invisible from the outside and each of which makes a session simply never come up:
Discovery that keeps trying. The RTL searches once, for three seconds, at the moment of joining, and never again. Whether the answer arrives inside that window is luck on Wi-Fi — a phone whose radio is in power save, an access point that holds a broadcast back, a device started a little later. The session repeats the search every few seconds until somebody is there, and gives up after about a minute rather than keeping the radio busy for the whole game.
Who connects to whom. Both devices discover each other in the same moment,
and the inherited version has each of them call Connect on the other. One of
the two is refused, the refusal tears the pair down again — "lost
communication" — and the user lists never line up. A refusal is harmless only
when it means the other side got there first, and the one thing that says so is
ConnectedProfiles: Connect records a profile there on its own success and
nowhere else, and an incoming connection never appears in this side's list.
So the session asks. If the profile is connected, it goes on to fetch the user
list, without which the member list stays empty while messages are visibly
arriving. If it is not, the connection simply failed, and the search repeat
tries it again — reading that case as the harmless one is what used to leave a
side connected, receiving messages, and alone at its own table.
The passive side of a pairing. The RTL discovers the other end's profiles, and with them its user list, only for the side that pairs actively. Its own repair for the other side — the reverse connect — misfires, because that handler starts by looking up a profile this side has never discovered. Whoever ends up passive is then connected and receiving messages with a member list of one, and a host in that position can never start the match; with a direct join by address, or one out of the lobby directory, that is always the host. The search repeat therefore also asks a paired manager for its profiles again, connects to a profile it knows but is not connected to, and asks who is there. All three are no-ops once they have taken, and the repeat stops as soon as somebody is found.
The Android multicast lock. Android hands multicast to an app only while it
holds a WifiManager multicast lock. Without one the Wi-Fi stack drops the
discovery packets before the app ever sees them — a session opened on the phone
is invisible to everybody, and one opened elsewhere stays invisible to the
phone. The lock is taken when a session opens and dropped when it closes, not
held for the life of the application, because it stops the Wi-Fi chip from
filtering in power save and costs battery.
The bind address. The manager picks one address on a machine with several
and binds tethering to it. On Windows that is what keeps a session from ever
being found: discovery goes out as a limited broadcast to 255.255.255.255,
and a socket bound to one address does not receive those — only a socket on
0.0.0.0 does. The session therefore overrides PickBindAddress to return an
empty string and lets the RTL bind every card, which is the case it was written
for. <PREFIX>_BIND still overrides everything.
Linux
App Tethering has no Linux implementation — it needs System.Bluetooth, which
does not exist there. On Linux the session derives from
TGorillaArenaCustomManager instead of TGorillaArenaManager, and every
session runs over atDirect, whatever Transport says (atBluetooth adds a
notice). Sessions, matches, the lobby directory, users and items work as on
every other platform.
The properties the tethering manager publishes elsewhere — Id,
DisplayName, Target, AllowedAdapters, BindToAddress — are published on
Linux under the same names, so a form designed on Windows loads unchanged. A
form unit that lists Gorilla.Arena.Manager in its uses (the IDE adds it for
the ancestor of the session) has to put it in {$IFNDEF LINUX}.
The Gorilla3D package carries every Arena unit on Linux except
Gorilla.Arena.Manager.
Diagnostics
Three environment variables, all prefixed with EnvPrefix:
| Variable | |
|---|---|
<PREFIX>_LOG |
Names a file to trace into |
<PREFIX>_BIND |
Names the network card by hand, overriding everything |
<PREFIX>_ADAPTERS |
Names the tethering adapters |
<PREFIX>_ADAPTERS takes names separated by semicolons or |, never by
commas: TTetheringManager.SetAllowedAdapters splits on those two only, an
unknown name matches no adapter, and the manager then registers none, listens
on nothing, and fails silently. The names are Network (plain UDP broadcast,
the RTL default), Network_V4 (multicast, despite the name) and Bluetooth.
Everything also goes to the platform log — adb logcat on Android, where there
is no console and no environment to point a variable at.
See Also
- Match — The layer above: seating, turns, host authority
- Arena Manager — The layer below
- Lobby Directory — Finding a session without typing an address
- Gorilla.Arena.Session — API reference
- Gorilla.Arena.Message — API reference