Hello! I am trying to implement independent network connection.
By “independent” I mean, server and client will reconnect each other and sync state after connection was lost.
So, for Server my NetworkManager works this way:
IEnumerator HandleServer()
{
while (true)
{
bool isConnected = false;
bool isError = false;
while (!isConnected)
{
if (isError)
{
Debug.Log("Waiting for 5 seconds becouse error!");
yield return new WaitForSeconds(5f);
}
try
{
discovery.Initialize();
discovery.StartAsServer();
manager.StartServer();
isConnected = true;
}
catch (Exception e)
{
// also I need to show it in my interface
isError = true;
LogMan.manager.AddLine("Error connecting to network! Trying again in 5 seconds." + e.ToString());
}
}
// wait while connection available
while (manager.isNetworkActive)
yield return null;
discovery.StopBroadcast();
manager.StopServer();
}
}
And for Client my NetworkManager works this way:
IEnumerator HandleClient()
{
while (true)
{
discovery.Initialize();
string serverAddress = null;
discovery.ReceiveBroadcast = (string fromAddress) => serverAddress = fromAddress;
discovery.StartAsClient();
// waiting while discovery will receive broadcast
while (serverAddress == null)
yield return null;
discovery.StopBroadcast();
manager.networkAddress = serverAddress;
manager.StartClient();
while (manager.isNetworkActive)
yield return null;
manager.StopClient();
}
}
First time it always connects properly. But after restarting Server, Client sometimes connects to server and sometimes not. I tryed to point out why thats happens, but I really have no idea.
It looks like sometimes at reconnection, server handle OnServerConnect event and then handle OnServerDisconnect, missing OnServerAddPlayer event. After that, connection on client becomes totally broken. When I restart Client, it works again.
Seem I need somehow reinitialize my client connection before reconnecting? But how can I do this?