I am using Relay + NGO.
When I to connect to a relay and start the client, sometimes, the client doesn’t connect to the host.
After that, it waits for like 20 seconds and then throws “Cannot connect to server” exception.
packages used:
Netcode for game objects version : 1.1.0
Relay version : 1.0.5
ParrelSync for testing out the project
Relay host functions
public async Task<RelayServerData> AllocateRelayServerAndGetJoinCode(int maxConnections, string region = null)
{
Allocation allocation;
string createJoinCode;
try
{
allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections, region);
}
catch (Exception e)
{
Debug.LogError($"Relay create allocation request failed {e.Message}");
throw;
}
Debug.Log($"server: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}");
Debug.Log($"server: {allocation.AllocationId}");
try
{
createJoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
joinCode = createJoinCode;
}
catch
{
Debug.LogError("Relay create join code request failed");
throw;
}
return new RelayServerData(allocation, "dtls");
}
public IEnumerator Example_ConfigureTransportAndStartNgoAsHost()
{
var serverRelayUtilityTask = AllocateRelayServerAndGetJoinCode(m_MaxConnections);
while (!serverRelayUtilityTask.IsCompleted)
{
yield return null;
}
if (serverRelayUtilityTask.IsFaulted)
{
Debug.LogError("Exception thrown when attempting to start Relay Server. Server not started. Exception: " + serverRelayUtilityTask.Exception.Message);
yield break;
}
var relayServerData = serverRelayUtilityTask.Result;
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData);
NetworkManager.Singleton.StartHost();
yield return null;
}
Relay client functions
public static async Task<RelayServerData> JoinRelayServerFromJoinCode(string joinCode)
{
JoinAllocation allocation;
try
{
allocation = await RelayService.Instance.JoinAllocationAsync(joinCode);
}
catch
{
Debug.LogError("Relay create join code request failed");
throw;
}
Debug.Log($"client: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}");
Debug.Log($"host: {allocation.HostConnectionData[0]} {allocation.HostConnectionData[1]}");
Debug.Log($"client: {allocation.AllocationId}");
return new RelayServerData(allocation, "dtls");
}
IEnumerator Example_ConfigureTransportAndStartNgoAsConnectingPlayer()
{
joinCode = joinCodeInputField.text;
// Populate RelayJoinCode beforehand through the UI
var clientRelayUtilityTask = JoinRelayServerFromJoinCode(joinCode);
while (!clientRelayUtilityTask.IsCompleted)
{
yield return null;
}
if (clientRelayUtilityTask.IsFaulted)
{
Debug.LogError("Exception thrown when attempting to connect to Relay Server. Exception: " + clientRelayUtilityTask.Exception.Message);
yield break;
}
var relayServerData = clientRelayUtilityTask.Result;
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData);
NetworkManager.Singleton.StartClient();
yield return null;
}