Skip to content

Commit 18026a9

Browse files
feat: connection management tests [MTT-3969] (#692)
* Adding tests for connection management * Passing NetworkManager through DI directly instead of as a serialized field of ConnectionManager * Renaming GameNetPortal prefab * Adding more verbosity to ConnectionManager's debug log on state changed * Exposing number of reconnection attempts as serialized field and property of ConnectionManager
1 parent e333c7e commit 18026a9

File tree

13 files changed

+569
-34
lines changed

13 files changed

+569
-34
lines changed

Assets/Prefabs/GameNetPortal.prefab renamed to Assets/Prefabs/ConnectionManager.prefab

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ GameObject:
1111
- component: {fileID: 5062837533140207352}
1212
- component: {fileID: 1984353324962460586}
1313
m_Layer: 0
14-
m_Name: GameNetPortal
15-
m_TagString: GameNetPortal
14+
m_Name: ConnectionManager
15+
m_TagString: Untagged
1616
m_Icon: {fileID: 0}
1717
m_NavMeshLayer: 0
1818
m_StaticEditorFlags: 0
@@ -44,6 +44,8 @@ MonoBehaviour:
4444
m_Script: {fileID: 11500000, guid: bf51ea31bbc84cc3aa883cc5f1caae06, type: 3}
4545
m_Name:
4646
m_EditorClassIdentifier:
47-
m_NetworkManager: {fileID: 0}
48-
m_AvatarRegistry: {fileID: 11400000, guid: 48d17d764bff6c643a3dc035fb71c979, type: 2}
49-
m_GameState: {fileID: 7151198093957655792, guid: 3af96a32a84bcf74d9538fa7af973c97, type: 3}
47+
m_NetworkObjectsToSpawnWhenServerStarted:
48+
- {fileID: 7151198093957655792, guid: 3af96a32a84bcf74d9538fa7af973c97, type: 3}
49+
MaxConnectedPlayers: 8
50+
m_OfflineScene: MainMenu
51+
m_StartScene: CharSelect

Assets/Scenes/Startup.unity

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
version https://git-lfs.github.com/spec/v1
2-
oid sha256:48a24b280794a53ab92b88c560dba8dddc996e910e534a952e60fa0bad85a1cc
3-
size 45753
2+
oid sha256:acddfdd76ba86ff45c5ee2c70038ee5a32336953be4735bfba3b740f1145d324
3+
size 45803

Assets/Scripts/ApplicationLifecycle/ApplicationController.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
66
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Infrastructure;
77
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
8+
using Unity.Netcode;
89
using UnityEngine;
910
using UnityEngine.SceneManagement;
1011
using VContainer;
@@ -20,6 +21,7 @@ public class ApplicationController : LifetimeScope
2021
{
2122
[SerializeField] UpdateRunner m_UpdateRunner;
2223
[SerializeField] ConnectionManager m_ConnectionManager;
24+
[SerializeField] NetworkManager m_NetworkManager;
2325

2426
LocalLobby m_LocalLobby;
2527
LobbyServiceFacade m_LobbyServiceFacade;
@@ -30,8 +32,8 @@ protected override void Configure(IContainerBuilder builder)
3032
{
3133
base.Configure(builder);
3234
builder.RegisterComponent(m_UpdateRunner);
33-
builder.RegisterComponent(m_ConnectionManager.NetworkManager);
3435
builder.RegisterComponent(m_ConnectionManager);
36+
builder.RegisterComponent(m_NetworkManager);
3537

3638
//the following singletons represent the local representations of the lobby that we're in and the user that we are
3739
//they can persist longer than the lifetime of the UI in MainMenu where we set up the lobby that we create or join

Assets/Scripts/ConnectionManagement/ConnectionManager.cs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,15 @@ public class ConnectionManager : MonoBehaviour
5656
{
5757
ConnectionState m_CurrentState;
5858

59-
[SerializeField]
59+
[Inject]
6060
NetworkManager m_NetworkManager;
6161
public NetworkManager NetworkManager => m_NetworkManager;
6262

63+
[SerializeField]
64+
int m_NbReconnectAttempts = 2;
65+
66+
public int NbReconnectAttempts => m_NbReconnectAttempts;
67+
6368
[Inject]
6469
IObjectResolver m_Resolver;
6570

@@ -106,7 +111,7 @@ void OnDestroy()
106111

107112
internal void ChangeState(ConnectionState nextState)
108113
{
109-
Debug.Log($"Changed connection state from {m_CurrentState.GetType().Name} to {nextState.GetType().Name}.");
114+
Debug.Log($"{name}: Changed connection state from {m_CurrentState.GetType().Name} to {nextState.GetType().Name}.");
110115

111116
if (m_CurrentState != null)
112117
{
@@ -185,23 +190,23 @@ void ReceiveServerToClientSetDisconnectReason_CustomMessage(ulong clientID, Fast
185190
/// Sends a DisconnectReason to all connected clients. This should only be done on the server, prior to disconnecting the clients.
186191
/// </summary>
187192
/// <param name="status"> The reason for the upcoming disconnect.</param>
188-
public static void SendServerToAllClientsSetDisconnectReason(ConnectStatus status)
193+
public void SendServerToAllClientsSetDisconnectReason(ConnectStatus status)
189194
{
190195
var writer = new FastBufferWriter(sizeof(ConnectStatus), Allocator.Temp);
191196
writer.WriteValueSafe(status);
192-
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(nameof(ReceiveServerToClientSetDisconnectReason_CustomMessage), writer);
197+
NetworkManager.CustomMessagingManager.SendNamedMessageToAll(nameof(ReceiveServerToClientSetDisconnectReason_CustomMessage), writer);
193198
}
194199

195200
/// <summary>
196201
/// Sends a DisconnectReason to the indicated client. This should only be done on the server, prior to disconnecting the client.
197202
/// </summary>
198203
/// <param name="clientID"> id of the client to send to </param>
199204
/// <param name="status"> The reason for the upcoming disconnect.</param>
200-
public static void SendServerToClientSetDisconnectReason(ulong clientID, ConnectStatus status)
205+
public void SendServerToClientSetDisconnectReason(ulong clientID, ConnectStatus status)
201206
{
202207
var writer = new FastBufferWriter(sizeof(ConnectStatus), Allocator.Temp);
203208
writer.WriteValueSafe(status);
204-
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(nameof(ReceiveServerToClientSetDisconnectReason_CustomMessage), clientID, writer);
209+
NetworkManager.CustomMessagingManager.SendNamedMessage(nameof(ReceiveServerToClientSetDisconnectReason_CustomMessage), clientID, writer);
205210
}
206211
}
207212
}

Assets/Scripts/ConnectionManagement/ConnectionState/ClientReconnectingState.cs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using System.Collections;
33
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
4-
using Unity.Netcode;
54
using UnityEngine;
65
using VContainer;
76

@@ -15,8 +14,6 @@ namespace Unity.Multiplayer.Samples.BossRoom
1514
/// </summary>
1615
class ClientReconnectingState : ClientConnectingState
1716
{
18-
const int k_NbReconnectAttempts = 2;
19-
2017
[Inject]
2118
IPublisher<ReconnectMessage> m_ReconnectMessagePublisher;
2219

@@ -38,7 +35,7 @@ public override void Exit()
3835
m_ConnectionManager.StopCoroutine(m_ReconnectCoroutine);
3936
m_ReconnectCoroutine = null;
4037
}
41-
m_ReconnectMessagePublisher.Publish(new ReconnectMessage(k_NbReconnectAttempts, k_NbReconnectAttempts));
38+
m_ReconnectMessagePublisher.Publish(new ReconnectMessage(m_ConnectionManager.NbReconnectAttempts, m_ConnectionManager.NbReconnectAttempts));
4239
}
4340

4441
public override void OnClientConnected(ulong _)
@@ -48,7 +45,7 @@ public override void OnClientConnected(ulong _)
4845

4946
public override void OnClientDisconnect(ulong _)
5047
{
51-
if (m_NbAttempts < k_NbReconnectAttempts)
48+
if (m_NbAttempts < m_ConnectionManager.NbReconnectAttempts)
5249
{
5350
m_ReconnectCoroutine = m_ConnectionManager.StartCoroutine(ReconnectCoroutine());
5451
}
@@ -76,11 +73,11 @@ IEnumerator ReconnectCoroutine()
7673
{
7774
Debug.Log("Lost connection to host, trying to reconnect...");
7875

79-
NetworkManager.Singleton.Shutdown();
76+
m_ConnectionManager.NetworkManager.Shutdown();
8077

81-
yield return new WaitWhile(() => NetworkManager.Singleton.ShutdownInProgress); // wait until NetworkManager completes shutting down
82-
Debug.Log($"Reconnecting attempt {m_NbAttempts + 1}/{k_NbReconnectAttempts}...");
83-
m_ReconnectMessagePublisher.Publish(new ReconnectMessage(m_NbAttempts, k_NbReconnectAttempts));
78+
yield return new WaitWhile(() => m_ConnectionManager.NetworkManager.ShutdownInProgress); // wait until NetworkManager completes shutting down
79+
Debug.Log($"Reconnecting attempt {m_NbAttempts + 1}/{m_ConnectionManager.NbReconnectAttempts}...");
80+
m_ReconnectMessagePublisher.Publish(new ReconnectMessage(m_NbAttempts, m_ConnectionManager.NbReconnectAttempts));
8481
m_NbAttempts++;
8582
if (!string.IsNullOrEmpty(m_LobbyCode))
8683
{

Assets/Scripts/ConnectionManagement/ConnectionState/HostingState.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public override void OnClientDisconnect(ulong clientId)
7575

7676
public override void OnUserRequestedShutdown()
7777
{
78-
ConnectionManager.SendServerToAllClientsSetDisconnectReason(ConnectStatus.HostEndedSession);
78+
m_ConnectionManager.SendServerToAllClientsSetDisconnectReason(ConnectStatus.HostEndedSession);
7979
// Wait before shutting down to make sure clients receive that message before they are disconnected
8080
m_ConnectionManager.StartCoroutine(WaitToShutdown());
8181
}
@@ -129,12 +129,12 @@ IEnumerator WaitToDenyApproval()
129129
{
130130
response.Pending = true; // give some time for server to send connection status message to clients
131131
response.Approved = false;
132-
ConnectionManager.SendServerToClientSetDisconnectReason(clientId, gameReturnStatus);
132+
m_ConnectionManager.SendServerToClientSetDisconnectReason(clientId, gameReturnStatus);
133133
yield return null; // wait a frame so UTP can flush it's messages on next update
134134
response.Pending = false; // connection approval process can be finished.
135135
}
136136

137-
ConnectionManager.SendServerToClientSetDisconnectReason(clientId, gameReturnStatus);
137+
m_ConnectionManager.SendServerToClientSetDisconnectReason(clientId, gameReturnStatus);
138138
m_ConnectionManager.StartCoroutine(WaitToDenyApproval());
139139
if (m_LobbyServiceFacade.CurrentUnityLobby != null)
140140
{

Assets/Scripts/ConnectionManagement/ConnectionState/OfflineState.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public override void StartClientLobby(string playerName)
5454

5555
public override void StartHostIP(string playerName, string ipaddress, int port)
5656
{
57-
var utp = (UnityTransport)NetworkManager.Singleton.NetworkConfig.NetworkTransport;
57+
var utp = (UnityTransport)m_ConnectionManager.NetworkManager.NetworkConfig.NetworkTransport;
5858
utp.SetConnectionData(ipaddress, (ushort)port);
5959

6060
SetConnectionPayload(GetPlayerId(), playerName);

0 commit comments

Comments
 (0)