Unity Networking No Master Server

Unity3d networking requires a 'master server' live on the Internet to join users to games and handle any NAT punch through issues. Note that development builds by default use a temporary test master server hosted by Unity not intended to be used by production games. Any online hosting is going to have an ongoing cost to a published game. The following is a proof of concept for connecting players to each other via WiFi from within a local subnet (actually in this case, players behind a single router).

Note that Unity Free edition does not support .NET Sockets on iOS or Android. This sample includes a basic backend for .NET Sockets on PC and a Java backend for Android (also the only way this code has been tested).

This proof of concept is derived from a Unity networking tutorial that uses the standard master server. Calls to the 'MasterServer' class have been replaced with calls to a new class 'NoMasterServer'. The basic premis is thus:

  • When a server is launched (NoMasterServer.RegisterHost) it broadcasts it presence for up to a minute, or until it has attached the maximum number of clients (as per 'Network.maxConnections').
  • When a client requests a list of servers (NoMasterServer.RequestHostList) it waits for a few seconds for any server broadcast in progress
  • Included in the server broadcast is the RakNet network UID of the server, the IP address and the port to connect to.  Clients use this information when connecting.

This code can be a little fragile due to the interaction between managed (C#/Java) code and unmanaged OS sockets.  Sockets are only closed and destroyed when required (a second call to a socket previously open on a given port reuses the existing socket object).

Technologies: Android, Java, C#, Unity.

 

File Attachments:  NoMasterServer_POC.7z (66Kb)