NAT Traversal for UNET
Provides NAT punch-through, automatic port forwarding, and other useful features on top of Unity's UNET HLAPI networking system.
NetworkManager Class Reference

Extends Unity's built in NetworkManager, adding NAT punch-through, automatic port forwarding, and some other nice features. More...

Inherits NetworkManager.

Public Member Functions

virtual void Awake ()
 
virtual NetworkConnection checkForAnotherConnectionFromTheSameClient (NetworkConnection con, ConnectionType otherConnectionType=ConnectionType.ANY)
 Checks for another connection from the same client as the passed in connection. More...
 
virtual NetworkClient createClient ()
 Create and configure a new NetworkClient. More...
 
virtual void directConnect (string externalIP, string internalIP, string hostExternalIPv6, string hostInternalIPv6)
 Attempt to connect directly to a host More...
 
virtual void finishShuttingDownHostWhenMatchIsUnlisted (bool success, string extendedInfo)
 
virtual IEnumerator getExternalIP ()
 Uses the externalIPSource to fetch the public facing IP. isDoneFetchingExternalIP will be set to true when the ip has either been succesfully fetched or the connection to externalIPSource has times out. More...
 
virtual IEnumerator getExternalIPv6 ()
 Uses the externalIPv6Source to fetch the public facing IP. isDoneFetchingExternalIPv6 will be set to true when the ip has either been succesfully fetched or the connection to externalIPv6Source has times out. More...
 
virtual string getLocalIPv6 ()
 Gets the local IPv6 address by looping through all network interfaces and returning first ipv6 address from the first interface whose OperationalStatus is Up. More...
 
virtual string GetMatchNameFromConnectionInfo ()
 Mash all the connection info into a string so we can use it as the match name. More...
 
virtual void initConfig ()
 Initialize the connectionConfig and hostTopology to use the settings from the Advanced Configuration section. More...
 
override void OnClientDisconnect (NetworkConnection conn)
 
override void OnClientSceneChanged (NetworkConnection conn)
 Called whenever a scene is loaded. More...
 
virtual void OnConnectionInfoConfirmationReceivedOnClient (NetworkMessage msg)
 When the host receives connection info it sends back a confirmation message which is received here on clients. More...
 
virtual void OnConnectionReplacedClient (NetworkConnection oldConnection, NetworkConnection newConnection)
 Called on the client when a relay connection has been replaced by a direct or punch-through connection. More...
 
virtual void OnConnectionReplacedServer (NetworkConnection oldConnection, NetworkConnection newConnection)
 Called on the server when a relay connection has been replaced by a direct or punch-through connection. More...
 
virtual void OnDoneConnectingToFacilitator (ulong guid)
 Override this method to be notified when the Facilitator is done being connected to. The method will be passed the guid that was assigned by the Facilitator. If the guid is 0 then connection failed. More...
 
virtual void OnHolePunchedClient (int natListenPort, int natConnectPort, bool success)
 Client punched through to a server. More...
 
virtual void OnHolePunchedServer (int natListenPort, ulong clientGUID)
 Server received a hole punch from a client. More...
 
virtual void OnMatchAttributesUpdated (bool success, string extendedInfo)
 
override void OnMatchCreate (bool success, string extendedInfo, MatchInfo matchInfo)
 This is invoked when a match has been created. More...
 
virtual void OnMatchDestroyed (bool success, string extendedInfo)
 
virtual void OnMatchDropped (bool success, string extendedInfo)
 
override void OnMatchJoined (bool success, string extendedInfo, MatchInfo info)
 Joins the match via relay unless a direct connection has already been established. More...
 
virtual void OnMultiClientConnect (NetworkConnection conn)
 Called when one of the multiple clients has connected and loaded the onlineScene (if there is one) More...
 
virtual void OnMultiClientDisconnect (NetworkConnection conn)
 Called when one of the multiple clients disconnects. More...
 
virtual void OnReadyToHostMatch ()
 Called when all connection data has been gathered that is needed to host a match More...
 
override void OnServerAddPlayer (NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
 Modified to get host migration working. If you override this make sure to call the base method or host migration will break. More...
 
override void OnServerAddPlayer (NetworkConnection conn, short playerControllerId)
 Modified to get host migration working. If you override this make sure to call the base method or host migration will break. More...
 
override void OnServerConnect (NetworkConnection conn)
 Called on the server when a new client connects. More...
 
override void OnServerDisconnect (NetworkConnection conn)
 Called on the server when a client disconnects. Note that there can be more than one client disconnect per connected peer since multiple clients are started and connected. More...
 
override void OnServerRemovePlayer (NetworkConnection conn, PlayerController player)
 Modified to get host migration working. If you override this make sure to call the base method or host migration will break. More...
 
virtual void OnSetConnectionInfo (NetworkMessage msg)
 Called when the server receives connection info from a connecting client. More...
 
virtual bool ParseConnectionInfoFromMatchName (string matchName, out string externalIP, out string internalIP, out string externalIPv6, out string internalIPv6, out int directConnectPort, out ulong guid)
 Pulls the connection info out of a match name so that it can be used to connect. More...
 
virtual string pickCorrectAddressToConnectTo (string hostExternalIP, string hostInternalIP, string hostExternalIPv6, string hostInternalIPv6)
 Picks the correct internal or external address to connect to. More...
 
virtual void ReconnectDirectClientToNewHost (string externalIP, int port, string internalIP="", string internalIPv6="", string externalIPv6="")
 
virtual void RegisterHandlerClient (short type, NetworkMessageDelegate handler)
 Register a handler for all clients, including the local client if called on the host. More...
 
virtual void replaceConnection (NetworkConnection oldConn, NetworkConnection newConn)
 Replace a connection by copying the playerControllers and clientOwnedObjects lists. The old connections playerControllers and clientOwnedObjects are cleared. Calles OnConnectionReplacedServer() and OnConnectionReplacedClient() before the connection is actually replaced. More...
 
virtual void Start ()
 Set everything up. More...
 
virtual void StartClientAll (MatchInfoSnapshot match, NetworkMatch.DataResponseDelegate< MatchInfo > callback=null, string matchPassword="", int eloScore=0, int requestDomain=0)
 Attempts to connect to the host of a match using all enabled methods. More...
 
virtual void StartClientAll (string hostExternalIP, string hostInternalIP, int directConnectPort=0, ulong hostGUID=0, NetworkID matchID=NetworkID.Invalid, string hostExternalIPv6="", string hostInternalIPv6="", NetworkMatch.DataResponseDelegate< MatchInfo > joinMatchCallback=null, string matchPassword="", int eloScore=0, int requestDomain=0)
 Attempts to connect to the host of a match using all enabled methods. More...
 
virtual NetworkClient StartHostAll (string matchName, uint maxPlayers, bool advertise=true, string password="", int eloScore=0, int requestDomain=0, int directConnectPort=0)
 Start hosting using all enabled methods. More...
 
bool StartServerAll (string matchName, uint maxPlayers, bool advertise=true, string password="", int eloScore=0, int requestDomain=0, int directConnectPort=0)
 Start a server using all enabled methods. More...
 
virtual new void StopClient ()
 Stops all the clients, stops punch-through, and clears the message handler list. More...
 
virtual new void StopHost ()
 Calls StopServer and StopClient More...
 
virtual new void StopServer ()
 Stops all the servers, stops listening for punch-through, and clears the list of natServers. More...
 
virtual void Update ()
 Calls Update() on each of the natServers so they will process and send messages. More...
 

Static Public Member Functions

static string BuildConnectionString (string matchName, string internalIP, string externalIP, string internalIPv6, string externalIPv6, int networkPort, ulong guid=0)
 

Public Attributes

bool autoConnectToFacilitator = true
 Immediately connect to the facilitator as soon as the NetworkManager starts. More...
 
Guid clientGUID
 
int clientPort = 0
 The port to connect from on the client when connecting directly. More...
 
bool connectDirectly = true
 Whether or not to connect directly when StartClientAll() or networkMatch.joinMatch() is called More...
 
HashSet< string > connectedClientGUIDs = new HashSet<string>()
 A list of all connected Client GUIDs. The only reason I'm even storing this is so that I can use the count to get the number of clients. More...
 
Dictionary< NetworkConnection, ConnectionInfoMessageconnectionInfoByConnection = new Dictionary<NetworkConnection, ConnectionInfoMessage>()
 Each client's connection info. Used in host migration and for other purposes. More...
 
bool connectPunchthrough = true
 Whether or not to connect via punch-through when StartClientAll() or networkMatch.joinMatch() is called More...
 
bool connectRelay = true
 Whether or not to connect via Unity's relay servers when StartClientAll() is called If you use Unity's matchmaking without connectRelay enabled some slots will still be used on the relays since Unity doesn't offer the option to list a match without at least the host taking up a slot. This means that you will see some CCU usage while in development, but no actual bandwidth will be used on the relays while connectRelays is disabled so once your game goes live it won't cost you a dime. Unity doesn't charge for CCU, only bandwidth. Similarly if you have connectRelay enabled but choose not to use Unity's matchmaking a UNet match will still be created since it is required for relay connections. More...
 
List< NetworkConnection > deferredConnections = new List<NetworkConnection>()
 Connections that have been deferred until after the onlineScene loads. More...
 
bool delayDirectConnection = false
 You can turn this on to give relay connections a chance to finish before a direct connection is made. This is useful for testing connection replacing. More...
 
NetworkClient directClient
 The client used for connecting directly. More...
 
string externalIP
 Your external IP. This is fetched from web server at externalIPSource. Check isDoneGettingExternalIP to see if it is done being fetched. More...
 
string externalIPSource = "http://ipv4.icanhazip.com"
 The web server to query to get the externalIP. More...
 
float externalIPTimeout = 10
 How long to wait before giving up fetching external IP, in seconds. More...
 
string externalIPv6
 Your external IPv6. This is fetched from web server at externalIPv6Source. Check isDoneGettingExternalIP to see if it is done being fetched. More...
 
string externalIPv6Source = "http://ipv6.icanhazip.com"
 The web server to query to get the externalIP. More...
 
bool hasEverConnected
 This will be set to true once a client has connected and loaded the onlineScene (if there is one set) More...
 
string hostExternalIP
 External IP of the host to connect to More...
 
string hostExternalIPv6
 External IPv6 of the host to connect to More...
 
string hostInternalIP
 Internal IP of the host More...
 
string hostInternalIPv6
 Internal IPv6 of the host More...
 
NetworkID matchID
 The NetworkID of the last match that was created or joined More...
 
NodeID matchmakingNodeID
 The nodeID of the this client's node in the matchmaking group More...
 
NATHelper natHelper
 The NATHelper instance used by the network manager for punchthrough and port forwarding. More...
 
List< ExternalServernatServers = new List<ExternalServer>()
 The list of external servers listening for connections via punch-through More...
 
NetworkClient punchthroughClient
 The client used for connecting via punch-through. More...
 
NetworkClient relayClient
 The client used for connecting via relay. More...
 
HostTopology topo
 The host topology used by all clients and the host. More...
 
bool useUnityMatchmaking = true
 Set to false to disable the default unity matchmaking. More...
 

Protected Member Functions

virtual void OnMultiClientConnectInternal (NetworkConnection conn)
 Called when one of the multiple clients received a CONNECT message from the host. More...
 

Protected Attributes

Dictionary< short, NetworkMessageDelegate > clientMsgHandlers = new Dictionary<short, NetworkMessageDelegate>()
 Keep track all all message handlers added to clients. When a new client is created it gets all the handlers added to it. More...
 
bool isDoneFetchingExternalIPv4
 The is will return true once the externalIPv4 is done being fetched or has failed to be fetched. More...
 
bool isDoneFetchingExternalIPv6
 The is will return true once the externalIPv6 is done being fetched or has failed to be fetched. More...
 

Properties

NetworkConnection directCon [get]
 The connection used when connecting directly More...
 
bool isDoneFetchingExternalIP [get]
 The is will return true once both externalIP's are done being fetched or have failed to be fetched. More...
 
bool isReadyForMatchmaking [get]
 Returns true when the server has gathered connection data and is ready to host a match More...
 
int maxClients [get]
 Maximum number of clients, including the host. More...
 
int numClients [get]
 The number of Clients, including the host. More...
 
NetworkConnection punchthroughCon [get]
 The connection used when connecting via punch-through More...
 
NetworkConnection relayCon [get]
 The connection used when connecting via relay More...
 

Detailed Description

Extends Unity's built in NetworkManager, adding NAT punch-through, automatic port forwarding, and some other nice features.

You can use this component directly or extend from it to create your own NetworkManager. Call StartHostAll() to get things going on the host. To get things started on the client get a list of matches and pass one of them in to StartClientAll().

Member Function Documentation

◆ checkForAnotherConnectionFromTheSameClient()

virtual NetworkConnection checkForAnotherConnectionFromTheSameClient ( NetworkConnection  con,
ConnectionType  otherConnectionType = ConnectionType.ANY 
)
virtual

Checks for another connection from the same client as the passed in connection.

This is called on the server to check if there is a direct connection from the same client as a disconnecting relay connection. It works by comparing a guid that is generated on the clients and sent to the server.

Parameters
conThe connection to check
Returns
A NetworkConnection with the same guid as the passed in connection if one exists. Null otherwise.

◆ createClient()

virtual NetworkClient createClient ( )
virtual

Create and configure a new NetworkClient.

Overrides the default Connect message handler to instead use OnMultiClientConnectMsg() so that we can deal with multiple clients connecting at once.

Returns
A newly configured NetworkClient

◆ directConnect()

virtual void directConnect ( string  externalIP,
string  internalIP,
string  hostExternalIPv6,
string  hostInternalIPv6 
)
virtual

Attempt to connect directly to a host

Parameters
externalIPThe external ip of the host to connec to
internalIPThe internal ip of the host to connect to

◆ getExternalIP()

virtual IEnumerator getExternalIP ( )
virtual

Uses the externalIPSource to fetch the public facing IP. isDoneFetchingExternalIP will be set to true when the ip has either been succesfully fetched or the connection to externalIPSource has times out.

◆ getExternalIPv6()

virtual IEnumerator getExternalIPv6 ( )
virtual

Uses the externalIPv6Source to fetch the public facing IP. isDoneFetchingExternalIPv6 will be set to true when the ip has either been succesfully fetched or the connection to externalIPv6Source has times out.

◆ getLocalIPv6()

virtual string getLocalIPv6 ( )
virtual

Gets the local IPv6 address by looping through all network interfaces and returning first ipv6 address from the first interface whose OperationalStatus is Up.

Returns
The local ipv6 address as a string or an empty string if there is none

◆ GetMatchNameFromConnectionInfo()

virtual string GetMatchNameFromConnectionInfo ( )
virtual

Mash all the connection info into a string so we can use it as the match name.

The guid is only included when connectPunchthrough is enabled.

Returns
matchName|hostInternalIP|hostExternalIP|hostInternalIPv6|hostExternalIPv6|networkPort|natHelper.guid

◆ initConfig()

virtual void initConfig ( )
virtual

Initialize the connectionConfig and hostTopology to use the settings from the Advanced Configuration section.

If the Advanced Configuraton checkbox is not checked then the default channels and match size are used. The default is a match size of four with one reliable sequenced channel and one unreliable channel.

◆ OnClientSceneChanged()

override void OnClientSceneChanged ( NetworkConnection  conn)

Called whenever a scene is loaded.

Calls OnMultiClientConnect() for each NetworkConnection in the deferredConnections list. Make sure to call base.OnClientSceneChanged() if you override this method.

Parameters
levelIDThe ID of the scene to load

◆ OnConnectionInfoConfirmationReceivedOnClient()

virtual void OnConnectionInfoConfirmationReceivedOnClient ( NetworkMessage  msg)
virtual

When the host receives connection info it sends back a confirmation message which is received here on clients.

The client has to wait to receive this message before replacing a relay connection with a direct connection, otherwise when the Host receives the ReplaceConnection message it may not be able to tell which connection to replace the relay connection with. Until the host receives the connection info it has no way to know which client a connection belongs to.

Parameters
msg

◆ OnConnectionReplacedClient()

virtual void OnConnectionReplacedClient ( NetworkConnection  oldConnection,
NetworkConnection  newConnection 
)
virtual

Called on the client when a relay connection has been replaced by a direct or punch-through connection.

Parameters
oldConnectionThe old relay connection
newConnectionThe new direct or punch-through connection

◆ OnConnectionReplacedServer()

virtual void OnConnectionReplacedServer ( NetworkConnection  oldConnection,
NetworkConnection  newConnection 
)
virtual

Called on the server when a relay connection has been replaced by a direct or punch-through connection.

Parameters
oldConnectionThe old relay connection
newConnectionThe new direct or punch-through connection

◆ OnDoneConnectingToFacilitator()

virtual void OnDoneConnectingToFacilitator ( ulong  guid)
virtual

Override this method to be notified when the Facilitator is done being connected to. The method will be passed the guid that was assigned by the Facilitator. If the guid is 0 then connection failed.

Parameters
guidThe guid assigned by the Facilitator or 0 on failure.

◆ OnHolePunchedClient()

virtual void OnHolePunchedClient ( int  natListenPort,
int  natConnectPort,
bool  success 
)
virtual

Client punched through to a server.

Attempts to connect through the hole. Make sure to call base.OnHolePunchedClient() if you override this method.

Parameters
natListenPortThe port on the client that the hole was punched from.
natConnectPortThe port on the server that was punched through to.

◆ OnHolePunchedServer()

virtual void OnHolePunchedServer ( int  natListenPort,
ulong  clientGUID 
)
virtual

Server received a hole punch from a client.

Starts up a new ExternalServer listening on the newly punched hole. Make sure to call base.OnHolePunchedServer() if you override this method.

Parameters
natListenPortThe port that a hole was just punched through on.

◆ OnMatchCreate()

override void OnMatchCreate ( bool  success,
string  extendedInfo,
MatchInfo  matchInfo 
)

This is invoked when a match has been created.

Even if connectRelay is false we still have to connect to the relay on the host otherwise the match will be delisted after 30 seconds for being empty. Make sure to call base.OnMatchCreate() if you override this method.

Parameters
matchInfoInfo about the match that has been created.

◆ OnMatchJoined()

override void OnMatchJoined ( bool  success,
string  extendedInfo,
MatchInfo  info 
)

Joins the match via relay unless a direct connection has already been established.

Make sure to call base.OnMatchJoined() if you override this method. If NAT punch-through and direct connection have not yet been started they will be started here but only if matchName was set to the name of the match being joined before networkMatch.JoinMatch() was called.

Parameters
resp

◆ OnMultiClientConnect()

virtual void OnMultiClientConnect ( NetworkConnection  conn)
virtual

Called when one of the multiple clients has connected and loaded the onlineScene (if there is one)

Because there are multiple connections per client this method may be called multiple times. If this is the first time a client has connected everthing proceeds as normal. If the relay client was already connected it is replaced by the new connection. If a non-relay client was already connected then the new connection is disconnected. Make sure to call base.OnMultiClientConnect() if you override this method.

Parameters
connThe connecting connection.

◆ OnMultiClientConnectInternal()

virtual void OnMultiClientConnectInternal ( NetworkConnection  conn)
protectedvirtual

Called when one of the multiple clients received a CONNECT message from the host.

Override this method if you need to be notified of clients connecting before they have loaded the onlineScene. Because there are multiple clients attempting to connect this method may be called multiple times. The client's internal and external ip are sent to the host. If the onlineScene is already loaded (or there is none) then OnMultiClientConnect() is called immediately. If the onlineScene is not yet loaded the connection is added to the deferredConnections list. OnMultiClientConnect() will be called for each connection in the list when the scene loads.

Parameters
connThe connecting connection.

◆ OnMultiClientDisconnect()

virtual void OnMultiClientDisconnect ( NetworkConnection  conn)
virtual

Called when one of the multiple clients disconnects.

Only calls OnClientDisconnect() if the client disconnecting is the current client that is actually being used. For example OnClientDisconnect() is not called when the relay client is disconnected because a direct connection already exists since this.client != relayClient

Parameters
connThe disconnecting connection.

◆ OnReadyToHostMatch()

virtual void OnReadyToHostMatch ( )
virtual

Called when all connection data has been gathered that is needed to host a match

If you're using UNET mathmaking you don't need to do override this. If you are using custom matchmaking you should override this method and create your match here. When this method is called externalIP, externalIPv6, guid, and matchID will all be populated. If "Connect Punchthrough" is not enabled then guid will be natHelper.guid will be 0. If "Connect relay" and "Use Unity Matchmaking" are not enabled then matchID will be NetworkId.Invalid

◆ OnServerAddPlayer() [1/2]

override void OnServerAddPlayer ( NetworkConnection  conn,
short  playerControllerId,
NetworkReader  extraMessageReader 
)

Modified to get host migration working. If you override this make sure to call the base method or host migration will break.

Parameters
conn
player

◆ OnServerAddPlayer() [2/2]

override void OnServerAddPlayer ( NetworkConnection  conn,
short  playerControllerId 
)

Modified to get host migration working. If you override this make sure to call the base method or host migration will break.

Parameters
conn
player

◆ OnServerConnect()

override void OnServerConnect ( NetworkConnection  conn)

Called on the server when a new client connects.

Registers a listener for SetConnectionInfo messages so that the server can be informed of the internal and external ip associated with each connection. Make sure to call base.OnServerConnect() if you override this method.

Parameters
connConnection from client.

◆ OnServerDisconnect()

override void OnServerDisconnect ( NetworkConnection  conn)

Called on the server when a client disconnects. Note that there can be more than one client disconnect per connected peer since multiple clients are started and connected.

If the connection that is disconnecting is the only connection from the associated client then it is disconnected as normal, unspawning any owned players / objects. If the connection that is disconnecting is a relay connection, and there is a direct connection from the same internal and external ip, then the relay connections's properties are copied over to the direct connection so that it can take over. Make sure to call base.OnServerDisconnect() if you override this method. You can use checkForAnotherConnectionFromTheSameClient() to check if a disconnecting connection is the last connection for a peer.

Parameters
connConnection from disconnecting client

◆ OnServerRemovePlayer()

override void OnServerRemovePlayer ( NetworkConnection  conn,
PlayerController  player 
)

Modified to get host migration working. If you override this make sure to call the base method or host migration will break.

Parameters
conn
player

◆ OnSetConnectionInfo()

virtual void OnSetConnectionInfo ( NetworkMessage  msg)
virtual

Called when the server receives connection info from a connecting client.

I suspect there is a better way of getting the internal and external ip for each connection but I couldn't figure it out. We keep track of this on the server so that when OnServerDisconnect is called we can figure out whether or not to actually drop the client. Make sure to call base.OnSetConnectionInfo() if you override this method.

Parameters
msgThe SetConnectionInfoMessage containing the ip addresses

◆ ParseConnectionInfoFromMatchName()

virtual bool ParseConnectionInfoFromMatchName ( string  matchName,
out string  externalIP,
out string  internalIP,
out string  externalIPv6,
out string  internalIPv6,
out int  directConnectPort,
out ulong  guid 
)
virtual

Pulls the connection info out of a match name so that it can be used to connect.

Parameters
matchNameName of the match.
externalIP[OUT] The the host's external ipv4.
internalIP[OUT] The host's internal ipv4.
externalIPv6[OUT] The host's external ipv6.
internalIPv6[OUT] The host's internal ipv6.
directConnectPort[OUT] The host's direct connect port.
guid[OUT] host's GUID provided by the Facilitator.

◆ pickCorrectAddressToConnectTo()

virtual string pickCorrectAddressToConnectTo ( string  hostExternalIP,
string  hostInternalIP,
string  hostExternalIPv6,
string  hostInternalIPv6 
)
virtual

Picks the correct internal or external address to connect to.

Most of the time we connect to the externalIP but when connecting to another PC on the same local network or another build on the same computer we need to use the local address or localhost instead

Parameters
hostExternalIPThe host external ip.
hostInternalIPThe host internal ip.
Returns
The address to connect to

◆ RegisterHandlerClient()

virtual void RegisterHandlerClient ( short  type,
NetworkMessageDelegate  handler 
)
virtual

Register a handler for all clients, including the local client if called on the host.

You should use this instead of client.RegisterHandler since there can be multiple clients and you want to make sure they all get the message. Clients that don't yet exist when this method is called will have the handler added when thet are created by createClient().

Parameters
typeMsgType to handle
handlerMethod to call when MsgType is received

◆ replaceConnection()

virtual void replaceConnection ( NetworkConnection  oldConn,
NetworkConnection  newConn 
)
virtual

Replace a connection by copying the playerControllers and clientOwnedObjects lists. The old connections playerControllers and clientOwnedObjects are cleared. Calles OnConnectionReplacedServer() and OnConnectionReplacedClient() before the connection is actually replaced.

Parameters
oldConn
newConn

◆ Start()

virtual void Start ( )
virtual

Set everything up.

Initializes the NATHelper to help with punching holes and port fowarding. Fetches the externalIP. Adds the NetworkMatch component so we can start matches later. Make sure to call base.Start() if you override this method.

◆ StartClientAll() [1/2]

virtual void StartClientAll ( MatchInfoSnapshot  match,
NetworkMatch.DataResponseDelegate< MatchInfo >  callback = null,
string  matchPassword = "",
int  eloScore = 0,
int  requestDomain = 0 
)
virtual

Attempts to connect to the host of a match using all enabled methods.

Simultaneously initiates a direct connection, starts punching a hole, and joins a NetworkMatch. The first connection to succeed will be used, but if it is a relay connection it may later be replaced by a non-relay connection if one is established. This ensures that clients are always connected using the best connection possible.

Parameters
matchThe match to get the connection info from.
callbackThe method to call when the UNET match has been joined.
matchPasswordThe match password.
eloScoreThe elo score.
requestDomainThe request domain.

◆ StartClientAll() [2/2]

virtual void StartClientAll ( string  hostExternalIP,
string  hostInternalIP,
int  directConnectPort = 0,
ulong  hostGUID = 0,
NetworkID  matchID = NetworkID.Invalid,
string  hostExternalIPv6 = "",
string  hostInternalIPv6 = "",
NetworkMatch.DataResponseDelegate< MatchInfo >  joinMatchCallback = null,
string  matchPassword = "",
int  eloScore = 0,
int  requestDomain = 0 
)
virtual

Attempts to connect to the host of a match using all enabled methods.

Parameters
hostExternalIPThe external IP of the host.
hostInternalIPThe internal IP of the host.
directConnectPortThe port to directly connect to.
hostGUIDThe RakNet guid of the host, obtained from the NATHelper.
matchIDThe NetworkID of the UNET match to join.
joinMatchCallbackThe method to call when the UNET match is joined.
matchPasswordThe match password.
eloScoreThe elo score.
requestDomainThe request domain.

Simultaneously initiates a direct connection, starts punching a hole, and joins a NetworkMatch. The first connection to succeed will be used, but if it is a relay connection it may later be replaced by a non-relay connection if one is established. This ensures that clients are always connected using the best connection possible.

◆ StartHostAll()

virtual NetworkClient StartHostAll ( string  matchName,
uint  maxPlayers,
bool  advertise = true,
string  password = "",
int  eloScore = 0,
int  requestDomain = 0,
int  directConnectPort = 0 
)
virtual

Start hosting using all enabled methods.

Parameters
matchNameName of the match.
maxPlayersThe maximum number of players.
advertiseShould the match be advertised?
passwordOptional password for the match.
eloScoreThe elo score.
requestDomainThe request domain.
directConnectPortThe port to host on for direct connections. Leave as 0 to use networkPort.
Returns
The local client.

Calls StartHost immediately to begin listening for direct connections and also so that the local client can connect and the host can get in game asap. Attempts to forward the networkPort if the host is behind a router and automatic port-fowarding (upnp) is enabled. Also starts listening for NAT punch-through attempts so that if upnp is not enabled or the port mapping fails clients can still directly connect. Also creates a UNET match so that if clients can not punch through they can still connect via relay as a last resort.

◆ StartServerAll()

bool StartServerAll ( string  matchName,
uint  maxPlayers,
bool  advertise = true,
string  password = "",
int  eloScore = 0,
int  requestDomain = 0,
int  directConnectPort = 0 
)

Start a server using all enabled methods.

Parameters
matchNameName of the match.
maxPlayersThe maximum number of players.
advertiseShould the match be advertised?
passwordOptional password for the match.
eloScoreThe elo score.
requestDomainThe request domain.
directConnectPortThe port to host on for direct connections. Leave as 0 to use networkPort.
Returns

◆ StopClient()

virtual new void StopClient ( )
virtual

Stops all the clients, stops punch-through, and clears the message handler list.

◆ StopHost()

virtual new void StopHost ( )
virtual

Calls StopServer and StopClient

◆ StopServer()

virtual new void StopServer ( )
virtual

Stops all the servers, stops listening for punch-through, and clears the list of natServers.

◆ Update()

virtual void Update ( )
virtual

Calls Update() on each of the natServers so they will process and send messages.

Make sure to call base.Update() if you override this method.

Member Data Documentation

◆ autoConnectToFacilitator

bool autoConnectToFacilitator = true

Immediately connect to the facilitator as soon as the NetworkManager starts.

If you don't connect automatically you will have to connect manually by calling natHelper.connectToFacilitator();

◆ clientMsgHandlers

Dictionary<short, NetworkMessageDelegate> clientMsgHandlers = new Dictionary<short, NetworkMessageDelegate>()
protected

Keep track all all message handlers added to clients. When a new client is created it gets all the handlers added to it.

◆ clientPort

int clientPort = 0

The port to connect from on the client when connecting directly.

There is probably no reason to ever set this but I thought I would throw it in since it's something that this NetworkManager can do that Unity's built in NetworkManager can not. Leave set to 0 to use a random port, which is the default behaviour.

◆ connectDirectly

bool connectDirectly = true

Whether or not to connect directly when StartClientAll() or networkMatch.joinMatch() is called

◆ connectedClientGUIDs

HashSet<string> connectedClientGUIDs = new HashSet<string>()

A list of all connected Client GUIDs. The only reason I'm even storing this is so that I can use the count to get the number of clients.

◆ connectionInfoByConnection

Dictionary<NetworkConnection, ConnectionInfoMessage> connectionInfoByConnection = new Dictionary<NetworkConnection, ConnectionInfoMessage>()

Each client's connection info. Used in host migration and for other purposes.

We store the the client guid for each incoming connection on the server so that we can tell when there are multiple connections associated with the same client. This allows the host to determine if a client disconnect should be ignored or treated as a real disconnect.

◆ connectPunchthrough

bool connectPunchthrough = true

Whether or not to connect via punch-through when StartClientAll() or networkMatch.joinMatch() is called

◆ connectRelay

bool connectRelay = true

Whether or not to connect via Unity's relay servers when StartClientAll() is called If you use Unity's matchmaking without connectRelay enabled some slots will still be used on the relays since Unity doesn't offer the option to list a match without at least the host taking up a slot. This means that you will see some CCU usage while in development, but no actual bandwidth will be used on the relays while connectRelays is disabled so once your game goes live it won't cost you a dime. Unity doesn't charge for CCU, only bandwidth. Similarly if you have connectRelay enabled but choose not to use Unity's matchmaking a UNet match will still be created since it is required for relay connections.

◆ deferredConnections

List<NetworkConnection> deferredConnections = new List<NetworkConnection>()

Connections that have been deferred until after the onlineScene loads.

When a client connects while in the offlineScene the call to OnClientConnect must be deferred until after the client has finished loading the onlineScene. Connections are added to this list as they are established. When OnLevelWasLoaded() gets called each of the connections will be passed to OnMultiClientConnect(). The first connection to succeed will be passed along to OnClientConnect().

◆ delayDirectConnection

bool delayDirectConnection = false

You can turn this on to give relay connections a chance to finish before a direct connection is made. This is useful for testing connection replacing.

◆ directClient

NetworkClient directClient

The client used for connecting directly.

◆ externalIP

string externalIP

Your external IP. This is fetched from web server at externalIPSource. Check isDoneGettingExternalIP to see if it is done being fetched.

◆ externalIPSource

string externalIPSource = "http://ipv4.icanhazip.com"

The web server to query to get the externalIP.

If you want to host this yourself the easiest way is to use a php script that looks something like:

<?PHP echo $_SERVER["REMOTE_ADDR"]; ?>

◆ externalIPTimeout

float externalIPTimeout = 10

How long to wait before giving up fetching external IP, in seconds.

◆ externalIPv6

string externalIPv6

Your external IPv6. This is fetched from web server at externalIPv6Source. Check isDoneGettingExternalIP to see if it is done being fetched.

◆ externalIPv6Source

string externalIPv6Source = "http://ipv6.icanhazip.com"

The web server to query to get the externalIP.

◆ hasEverConnected

bool hasEverConnected

This will be set to true once a client has connected and loaded the onlineScene (if there is one set)

◆ hostExternalIP

string hostExternalIP

External IP of the host to connect to

◆ hostExternalIPv6

string hostExternalIPv6

External IPv6 of the host to connect to

◆ hostInternalIP

string hostInternalIP

Internal IP of the host

◆ hostInternalIPv6

string hostInternalIPv6

Internal IPv6 of the host

◆ isDoneFetchingExternalIPv4

bool isDoneFetchingExternalIPv4
protected

The is will return true once the externalIPv4 is done being fetched or has failed to be fetched.

◆ isDoneFetchingExternalIPv6

bool isDoneFetchingExternalIPv6
protected

The is will return true once the externalIPv6 is done being fetched or has failed to be fetched.

◆ matchID

NetworkID matchID

The NetworkID of the last match that was created or joined

◆ matchmakingNodeID

NodeID matchmakingNodeID

The nodeID of the this client's node in the matchmaking group

◆ natHelper

NATHelper natHelper

The NATHelper instance used by the network manager for punchthrough and port forwarding.

◆ natServers

List<ExternalServer> natServers = new List<ExternalServer>()

The list of external servers listening for connections via punch-through

Each time the host receives a punch-through from a client an ExternalServer is started and added to this list.

◆ punchthroughClient

NetworkClient punchthroughClient

The client used for connecting via punch-through.

◆ relayClient

NetworkClient relayClient

The client used for connecting via relay.

◆ topo

HostTopology topo

The host topology used by all clients and the host.

If this isn't the same everywhere you will get CRC errors when you try and connect.

◆ useUnityMatchmaking

bool useUnityMatchmaking = true

Set to false to disable the default unity matchmaking.

By default when StartHostAll() is called a match is created on Unity's matchmaking servers. If you don't want to use Unity's matchmaking / relays at all you can disable both this option and connectRelay, but you'll have to implement your own method of passing around the connection info (such as our Match Up asset or Steam lobbies). If you use Unity's matchmaking without connectRelay enabled some slots will still be used on the relays since Unity doesn't offer the option to list a match without at least the host taking up a slot. This means that you will see some CCU usage while in development, but no actual bandwidth will be used on the relays while connectRelays is disabled so once your game goes live it won't cost you a dime. Unity doesn't charge for CCU, only bandwidth.

Property Documentation

◆ directCon

NetworkConnection directCon
get

The connection used when connecting directly

◆ isDoneFetchingExternalIP

bool isDoneFetchingExternalIP
getprotected

The is will return true once both externalIP's are done being fetched or have failed to be fetched.

◆ isReadyForMatchmaking

bool isReadyForMatchmaking
get

Returns true when the server has gathered connection data and is ready to host a match

Consider overridding OnReadyToHostMatch() instead of checking this property.

◆ maxClients

int maxClients
get

Maximum number of clients, including the host.

If customConfig is checked this will be maxConnections + 1 If customConfig is not checked this will by matchSize Note that NetworkServer.hostTopology.MaxDefaultConnections will be double the expected value. This is due to the fact that each client may have a relay connection and a direct connection at the same time to the same transport level host on the server so we have to make room for both or UNet will reject the connection at the transport level.

◆ numClients

int numClients
get

The number of Clients, including the host.

This is different than the number of Connections since each Client can have several Connections simultaneously.

◆ punchthroughCon

NetworkConnection punchthroughCon
get

The connection used when connecting via punch-through

◆ relayCon

NetworkConnection relayCon
get

The connection used when connecting via relay