Extend the server

Server packages

Server packages add code to the server itself: new message types, game rules, integrations and transports. The client side of your addon and the server side then talk over named plugin messages.

A server package runs inside the server process with its full privileges. Only install packages whose source you've read, and keep the list on each server short.

What a package is

A server package is a Unity package folder: a package.json with a name and version. Its server code compiles into one of the server's own assemblies, so it can use that assembly's internal members.

AssemblyRuns in
BasisNetworkCoreBoth the client and the server
BasisNetworkServerThe server, both standalone and when hosted inside Unity
BasisNetworkClientThe client, and the headless load-test client
BasisNetworkConsoleOnly the standalone server executable
BasisServerTestsThe server test project, so your tests run with dotnet test

The package manager finds your modules on its own:

  • An .asmref that points at BasisNetworkCore, BasisNetworkServer or BasisNetworkClient compiles its folder into that assembly.
  • A Server~/<assembly>/ folder holds server-only code. Unity never imports folders that end in ~.

Or name the modules, NuGet dependencies and prebuilt libraries yourself in package.json:

"basisServer": {
  "modules": [
    { "path": "Runtime/Network", "assembly": "BasisNetworkCore" },
    { "path": "Server~/Commands", "assembly": "BasisNetworkConsole" }
  ],
  "nuget": { "Some.Library": "1.2.3" },
  "references": [
    { "path": "Server~/Plugins/Example.dll", "assembly": "BasisNetworkCore", "platforms": ["win"] }
  ],
  "natives": [
    { "path": "Plugins/linux64/libexample.so", "assembly": "BasisNetworkCore", "platforms": "linux-x64" }
  ]
}

Shared code has to build as C# 9 for Unity and for both netstandard2.1 and net10.0 on the server. Inside a module, folders with their own .asmdef/.asmref, and folders whose names end in ~ or start with ., are left out, the same as in Unity.

Installing one

List the package in the server's manifest.json, the same way Unity does it: a git URL with #ref and ?path=, or a file: path. Then lock the versions with basispm server-install and restore them on build machines with basispm server-restore. To publish for another operating system, pass the runtime through: dotnet publish -r linux-x64 -p:BasisServerPackageRid=linux-x64.

Entry point

Mark one class per assembly as the package's entry point. It runs once per process. On the standalone server it runs before config.xml loads, so don't read configuration in Initialize. Wait for ServerStarted instead.

using Basis.Network.Core;

[assembly: BasisNetworkPackage(typeof(MorningBellPackage))]

public sealed class MorningBellPackage : IBasisNetworkPackage
{
    public void Initialize()
    {
        NetworkServer.ServerStarted += OnStarted;
        NetworkServer.ServerStopping += OnStopping;
    }

    private static void OnStarted(Configuration configuration) { /* start timers, open connections */ }
    private static void OnStopping() { /* flush and close */ }
}
Event on NetworkServerRaised
ServerStarted(Configuration)Once the server is listening
ConfigurationApplied(Configuration)After a live config change, from /config or the admin panel
ServerStopping()Before the transports stop

If an entry point or a handler throws, the error is logged and the others still run. Run /packages in the server console, or basisctl /packages, to see which packages are built in and which entry points ran. Tests don't run entry points, so call your registration from the tests that need it.

Plugin messages

Core traffic uses network channels 0–59. Addon traffic shares channels 61 (reliable), 62 (sequenced) and 63 (unreliable), with each message tagged by a 16-bit id. You register messages by name, and the server assigns ids from 64 upwards. When a client connects, the server sends it the list of names and ids on channel 60. The client replies with the ids it can handle, and from then on the server only sends it those.

Server side

public const string BellMessage = "morningbell.ring";

public void Initialize()
{
    BasisServerMessageRegistry.RegisterServerPlugin(BellMessage, DeliveryMethod.ReliableOrdered, OnRing);
}

private static void OnRing(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod delivery)
{
    try
    {
        if (!reader.TryGetByte(out byte volume)) return;
        // ...validate, then act
        BasisServerMessageRegistry.SendToPeer(peer, BellMessage, writer => writer.Put(volume));
    }
    finally
    {
        reader.Recycle();
    }
}
  • Your handler owns the reader. Call reader.Recycle() in a finally, as the built-in relays do.
  • Ids follow registration order. Always register in the same order, so ids stay the same across restarts. Clients look ids up by name, so they don't depend on the numbers.
  • Treat every payload as hostile. Use the TryGet… readers, check lengths and ranges, and return early on bad input. The server warns a peer after 50 handler errors and disconnects it at 500.
  • SendToPeer returns false when the name isn't registered or the peer didn't subscribe to it. A SendToPeer<TState> overload avoids allocating a closure on hot paths.
  • Messages only arrive from peers that have signed in. Until a peer signs in, the server drops everything except the sign-in channel.

Other members: TryGetPluginId(name, out ushort id), UnregisterPlugin(ushort id), and the PeerSubscribed event, which fires when a client has reported its subscriptions.

Client side (Unity)

BasisClientMessageRegistry.RegisterClientPlugin(BellMessage, (peer, reader, channel, delivery) =>
{
    if (reader.TryGetByte(out byte volume)) PlayBell(volume);
});

if (BasisClientMessageRegistry.IsPluginSupplied(BellMessage))
{
    BasisClientMessageRegistry.Send(BellMessage, writer => writer.Put((byte)80));
}
  • Register from a [RuntimeInitializeOnLoadMethod] static method in your client assembly. On the client, the BasisNetworkPackage attribute is only picked up from code compiled into the framework's own network assemblies.
  • You can register before connecting. The handler is bound to the server's id when the server's message list arrives. OnSupplyApplied fires at that point.
  • Send returns false if this server doesn't run your package, so your addon can fall back gracefully on servers without it.
  • UnregisterClientPlugin(name) removes the handler.

The screen-share package (com.basis.screenshare, with BasisNetworkScreenShare on the server) is a complete working example of a client-and-server addon built this way.

Transport packages

Network transports are packages too. The default UDP transport, com.basis.transport.litenetlib, and the WebSocket transport, com.basis.transport.websocket, are the reference implementations. A transport registers itself with BasisNetworkStackRegistry.Register(id, displayName, factory), plus RegisterParser, RegisterProbe, RegisterAddressMatcher and the peer-to-peer factories as needed. It can keep settings in config/transports/<id>.xml through BasisTransportConfigStore.RegisterType. Servers pick transports with the NetworkStackId setting, for example litenetlib,websocket.

Stability

The server's internal classes aren't a frozen public API. They change as the upstream Basis project moves. Keep your package's surface small: the entry point, the lifecycle events and the plugin message registry. Run its tests against each new server release. The package format and the registry are the parts designed to be built on.