Skip to content

Commit 5d957fc

Browse files
committed
adapting branch to develop changes. applying changes to connection manager. things aren't fully tested yet
1 parent f4fa6b1 commit 5d957fc

29 files changed

+255
-1544
lines changed

Assets/Prefabs/State/CharSelectState.prefab

Lines changed: 0 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ GameObject:
1111
- component: {fileID: 3565665953789623676}
1212
- component: {fileID: 1092063945021251778}
1313
- component: {fileID: 3565665953789623675}
14-
- component: {fileID: 3565665953789623674}
1514
- component: {fileID: 3565665953789623673}
1615
m_Layer: 0
1716
m_Name: CharSelectState
@@ -67,64 +66,6 @@ MonoBehaviour:
6766
TypeName: Unity.Multiplayer.Samples.BossRoom.Shared.ApplicationController
6867
autoRun: 1
6968
autoInjectGameObjects: []
70-
--- !u!114 &3565665953789623674
71-
MonoBehaviour:
72-
m_ObjectHideFlags: 0
73-
m_CorrespondingSourceObject: {fileID: 0}
74-
m_PrefabInstance: {fileID: 0}
75-
m_PrefabAsset: {fileID: 0}
76-
m_GameObject: {fileID: 3565665953789623672}
77-
m_Enabled: 1
78-
m_EditorHideFlags: 0
79-
m_Script: {fileID: 11500000, guid: eca1f4b442326cc4d9be3975746b8cdb, type: 3}
80-
m_Name:
81-
m_EditorClassIdentifier:
82-
parentReference:
83-
TypeName: Unity.Multiplayer.Samples.BossRoom.Shared.ApplicationController
84-
autoRun: 1
85-
autoInjectGameObjects: []
86-
m_AnimationTriggerOnCharSelect: BeginRevive
87-
m_AnimationTriggerOnCharChosen: BeginRevive
88-
m_PlayerSeats:
89-
- {fileID: 0}
90-
- {fileID: 0}
91-
- {fileID: 0}
92-
- {fileID: 0}
93-
- {fileID: 0}
94-
- {fileID: 0}
95-
- {fileID: 0}
96-
- {fileID: 0}
97-
m_IdentifiersForEachPlayerNumber:
98-
- Indicator: {fileID: 21300000, guid: 4efd4bc875cf78440a2bba2df426df59, type: 3}
99-
Color: {r: 1, g: 0.9607843, b: 0.03529412, a: 1}
100-
- Indicator: {fileID: 21300000, guid: eb78c7426de84ba4fb581a39bd47e1ea, type: 3}
101-
Color: {r: 1, g: 0.25490198, b: 0.25882354, a: 1}
102-
- Indicator: {fileID: 21300000, guid: 9f3c077482954fd47ac14f226b754aa4, type: 3}
103-
Color: {r: 0.40392157, g: 0.6901961, b: 1, a: 1}
104-
- Indicator: {fileID: 21300000, guid: 354c9edfa39e18f4a8b4bbeab8afa08b, type: 3}
105-
Color: {r: 0, g: 1, b: 0.3882353, a: 1}
106-
- Indicator: {fileID: 21300000, guid: 96e799a96c02bea4bb1664c70d61a7fa, type: 3}
107-
Color: {r: 0.5882353, g: 0.03137255, b: 0.99215686, a: 1}
108-
- Indicator: {fileID: 21300000, guid: 9e74ea5f2c75a624e9d29ced68c1faa6, type: 3}
109-
Color: {r: 0, g: 0.72156864, b: 0.7137255, a: 1}
110-
- Indicator: {fileID: 21300000, guid: 4587568254b46b74382b2e5db4111e2e, type: 3}
111-
Color: {r: 0.99607843, g: 0.6745098, b: 0.03137255, a: 1}
112-
- Indicator: {fileID: 21300000, guid: 5e0531f7cad04b346bf05685f3b9a846, type: 3}
113-
Color: {r: 0.19215687, g: 0.03137255, b: 0.9882353, a: 1}
114-
m_NumPlayersText: {fileID: 0}
115-
m_ReadyButtonText: {fileID: 0}
116-
m_UIElementsForNoSeatChosen:
117-
- {fileID: 0}
118-
- {fileID: 0}
119-
m_UIElementsForSeatChosen:
120-
- {fileID: 0}
121-
- {fileID: 0}
122-
m_UIElementsForLobbyEnding:
123-
- {fileID: 0}
124-
m_UIElementsForFatalError:
125-
- {fileID: 0}
126-
m_ClassInfoBox: {fileID: 0}
127-
m_CharacterGraphicsParent: {fileID: 0}
12869
--- !u!114 &3565665953789623673
12970
MonoBehaviour:
13071
m_ObjectHideFlags: 0

Assets/Scenes/CharSelect.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:fe57cffed60d9bfe7f42257a90c3d6a2240755dcaa4e10ae0c745f6fb4aecd66
3-
size 45820
2+
oid sha256:a06acfa155439752257373f6de50ef7537ffab69441f348510b27b67fe160ce5
3+
size 11023

Assets/Scenes/CharSelectClient.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:f68dc57d9e3a00b2f19d34c09f557cf446454e78cd8c642f80c907a331097ff8
3-
size 41688
2+
oid sha256:0ddf334a7900d81da8171553af1e7bc5944cf76407f11f5d4fdeaded1dd3408c
3+
size 41757

Assets/Scenes/PostGame.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:ddaaa366f8d07e0e8347f5cecd0d7bd6b71715365ad0458a45667ce3463f3672
3-
size 67888
2+
oid sha256:fd2dd930d1ba9caf5d764182829b0adb9aa7fa891353c045b2d64f6b60801a3a
3+
size 71828

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:6edc8e7a2df8ce6d41dc598ab9bb8d8f0d1d7d15f2029bd6516b2e6a1007c9e2
3+
size 26512

Assets/Scenes/StartupClient.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:48124e4fb9d5e5df41281333f3190bee9e41ca11ea92817e04c932a73380a4a5
3-
size 20853
2+
oid sha256:cf1f956de879b24f5c3589de244cd9832911919b654dbcd41c886d115e3f73f0
3+
size 23348

Assets/Scripts/ApplicationLifecycle/ApplicationController.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,8 @@ private void Start()
9090
DontDestroyOnLoad(gameObject);
9191
DontDestroyOnLoad(m_UpdateRunner.gameObject);
9292
Application.targetFrameRate = 120;
93-
94-
NetworkManager.Singleton.OnClientConnectedCallback += OnClientStarted;
93+
94+
NetworkManager.Singleton.OnClientConnectedCallback += OnClientStarted;
9595
NetworkManager.Singleton.OnServerStarted += OnServerStarted;
9696
if (DedicatedServerUtilities.IsServerBuildTarget)
9797
{
@@ -101,8 +101,8 @@ private void Start()
101101
else
102102
{
103103
SceneManager.LoadScene(SceneNames.StartupClient, LoadSceneMode.Additive);
104-
SceneManager.LoadScene("MainMenu");
105-
}
104+
SceneManager.LoadScene(SceneNames.MainMenu);
105+
}
106106
}
107107

108108
protected override void OnDestroy()

Assets/Scripts/ConnectionManagement/ConnectionManager.cs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,13 @@ public class ConnectionManager : MonoBehaviour
7474
internal readonly ClientConnectedState m_ClientConnected = new ClientConnectedState();
7575
internal readonly ClientReconnectingState m_ClientReconnecting = new ClientReconnectingState();
7676
internal readonly DisconnectingWithReasonState m_DisconnectingWithReason = new DisconnectingWithReasonState();
77+
internal readonly ServerStartingState m_ServerStarting = new ServerStartingState();
78+
internal readonly ServerListeningState m_ServerListening = new ServerListeningState();
7779
internal readonly StartingHostState m_StartingHost = new StartingHostState();
7880
internal readonly HostingState m_Hosting = new HostingState();
7981

82+
public bool IsConnectedToHost { get; private set; }
83+
8084
void Awake()
8185
{
8286
DontDestroyOnLoad(gameObject);
@@ -104,17 +108,19 @@ void OnDestroy()
104108
NetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback;
105109
NetworkManager.OnServerStarted -= OnServerStarted;
106110
NetworkManager.ConnectionApprovalCallback -= ApprovalCheck;
107-
108111
}
109112

110113
internal void ChangeState(ConnectionState nextState)
111114
{
112115
Debug.Log($"Changed connection state from {m_CurrentState.GetType().Name} to {nextState.GetType().Name}.");
113116

117+
IsConnectedToHost = false;
118+
114119
if (m_CurrentState != null)
115120
{
116121
m_CurrentState.Exit();
117122
}
123+
118124
m_CurrentState = nextState;
119125
m_CurrentState.Enter();
120126
}
@@ -159,6 +165,11 @@ public void StartHostIp(string playerName, string ipaddress, int port)
159165
m_CurrentState.StartHostIP(playerName, ipaddress, port);
160166
}
161167

168+
public void StartServerIP(string ipaddress, int port)
169+
{
170+
m_CurrentState.StartServerIP(ipaddress, port);
171+
}
172+
162173
public void RequestShutdown()
163174
{
164175
m_CurrentState.OnUserRequestedShutdown();
@@ -167,10 +178,12 @@ public void RequestShutdown()
167178
/// <summary>
168179
/// Registers the message handler for custom named messages. This should only be done once StartClient has been
169180
/// called (start client will initialize NetworkSceneManager and CustomMessagingManager)
181+
/// This will override the message handler each time and will use this instance's method.
170182
/// </summary>
171183
public void RegisterCustomMessages()
172184
{
173185
NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(nameof(ReceiveServerToClientSetDisconnectReason_CustomMessage), ReceiveServerToClientSetDisconnectReason_CustomMessage);
186+
NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(nameof(ReceiveServertoClientSuccessPayload_CustomMessage), ReceiveServertoClientSuccessPayload_CustomMessage);
174187
}
175188

176189
void ReceiveServerToClientSetDisconnectReason_CustomMessage(ulong clientID, FastBufferReader reader)
@@ -201,5 +214,18 @@ public static void SendServerToClientSetDisconnectReason(ulong clientID, Connect
201214
writer.WriteValueSafe(status);
202215
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(nameof(ReceiveServerToClientSetDisconnectReason_CustomMessage), clientID, writer);
203216
}
217+
218+
public void ReceiveServertoClientSuccessPayload_CustomMessage(ulong clientID, FastBufferReader reader)
219+
{
220+
reader.ReadValueSafe(out bool isHost);
221+
IsConnectedToHost = isHost;
222+
}
223+
224+
public static void SendServertoClientSuccessPayload(ulong clientID, bool isHost)
225+
{
226+
var writer = new FastBufferWriter(sizeof(bool), Allocator.Temp);
227+
writer.WriteValueSafe(isHost);
228+
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(nameof(ReceiveServertoClientSuccessPayload_CustomMessage), clientID, writer);
229+
}
204230
}
205231
}

Assets/Scripts/ConnectionManagement/ConnectionState/ConnectionState.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ public virtual void StartClientLobby(string playerName) { }
3232

3333
public virtual void StartHostIP(string playerName, string ipaddress, int port) { }
3434

35+
public virtual void StartServerIP(string ipaddress, int port) { }
36+
3537
public virtual void StartHostLobby(string playerName) { }
3638

3739
public virtual void OnUserRequestedShutdown() { }

Assets/Scripts/ConnectionManagement/ConnectionState/HostingState.cs

Lines changed: 9 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -13,154 +13,31 @@ namespace Unity.Multiplayer.Samples.BossRoom
1313
/// Connection state corresponding to a listening host. Handles incoming client connections. When shutting down or
1414
/// being timed out, transitions to the Offline state.
1515
/// </summary>
16-
class HostingState : ConnectionState
16+
class HostingState : ServerListeningState
1717
{
18-
[Inject]
19-
LobbyServiceFacade m_LobbyServiceFacade;
20-
[Inject]
21-
IPublisher<ConnectionEventMessage> m_ConnectionEventPublisher;
22-
23-
// used in ApprovalCheck. This is intended as a bit of light protection against DOS attacks that rely on sending silly big buffers of garbage.
24-
const int k_MaxConnectPayload = 1024;
25-
26-
public override void Enter()
27-
{
28-
var gameState = UnityEngine.Object.Instantiate(m_ConnectionManager.GameState);
29-
30-
gameState.Spawn();
31-
32-
SceneLoaderWrapper.Instance.AddOnSceneEventCallback();
33-
34-
//The "BossRoom" server always advances to CharSelect immediately on start. Different games
35-
//may do this differently.
36-
SceneLoaderWrapper.Instance.LoadScene("CharSelect", useNetworkSceneManager: true);
37-
}
38-
39-
public override void Exit()
40-
{
41-
SessionManager<SessionPlayerData>.Instance.OnServerEnded();
42-
}
43-
44-
public override void OnClientConnected(ulong clientId)
45-
{
46-
m_ConnectionEventPublisher.Publish(new ConnectionEventMessage() { ConnectStatus = ConnectStatus.Success, PlayerName = SessionManager<SessionPlayerData>.Instance.GetPlayerData(clientId)?.PlayerName });
47-
}
48-
49-
public override void OnClientDisconnect(ulong clientId)
50-
{
51-
if (clientId == m_ConnectionManager.NetworkManager.LocalClientId)
52-
{
53-
m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
54-
}
55-
else
56-
{
57-
var playerId = SessionManager<SessionPlayerData>.Instance.GetPlayerId(clientId);
58-
if (playerId != null)
59-
{
60-
if (m_LobbyServiceFacade.CurrentUnityLobby != null)
61-
{
62-
m_LobbyServiceFacade.RemovePlayerFromLobbyAsync(playerId, m_LobbyServiceFacade.CurrentUnityLobby.Id);
63-
}
64-
65-
var sessionData = SessionManager<SessionPlayerData>.Instance.GetPlayerData(playerId);
66-
if (sessionData.HasValue)
67-
{
68-
m_ConnectionEventPublisher.Publish(new ConnectionEventMessage() { ConnectStatus = ConnectStatus.GenericDisconnect, PlayerName = sessionData.Value.PlayerName });
69-
}
70-
SessionManager<SessionPlayerData>.Instance.DisconnectClient(clientId);
71-
}
72-
}
73-
}
74-
7518
public override void OnUserRequestedShutdown()
7619
{
7720
ConnectionManager.SendServerToAllClientsSetDisconnectReason(ConnectStatus.HostEndedSession);
7821
// Wait before shutting down to make sure clients receive that message before they are disconnected
7922
m_ConnectionManager.StartCoroutine(WaitToShutdown());
8023
}
8124

82-
/// <summary>
83-
/// This logic plugs into the "ConnectionApprovalResponse" exposed by Netcode.NetworkManager. It is run every time a client connects to us.
84-
/// The complementary logic that runs when the client starts its connection can be found in ClientConnectingState.
85-
/// </summary>
86-
/// <remarks>
87-
/// Multiple things can be done here, some asynchronously. For example, it could authenticate your user against an auth service like UGS' auth service. It can
88-
/// also send custom messages to connecting users before they receive their connection result (this is useful to set status messages client side
89-
/// when connection is refused, for example).
90-
/// </remarks>
91-
/// <param name="request"> The initial request contains, among other things, binary data passed into StartClient. In our case, this is the client's GUID,
92-
/// which is a unique identifier for their install of the game that persists across app restarts.
93-
/// <param name="response"> Our response to the approval process. In case of connection refusal with custom return message, we delay using the Pending field.
94-
public override void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
25+
IEnumerator WaitToShutdown()
9526
{
96-
var connectionData = request.Payload;
97-
var clientId = request.ClientNetworkId;
98-
if (connectionData.Length > k_MaxConnectPayload)
99-
{
100-
// If connectionData too high, deny immediately to avoid wasting time on the server. This is intended as
101-
// a bit of light protection against DOS attacks that rely on sending silly big buffers of garbage.
102-
response.Approved = false;
103-
return;
104-
}
105-
106-
var payload = System.Text.Encoding.UTF8.GetString(connectionData);
107-
var connectionPayload = JsonUtility.FromJson<ConnectionPayload>(payload); // https://docs.unity3d.com/2020.2/Documentation/Manual/JSONSerialization.html
108-
var gameReturnStatus = GetConnectStatus(connectionPayload);
109-
110-
if (gameReturnStatus == ConnectStatus.Success)
111-
{
112-
SessionManager<SessionPlayerData>.Instance.SetupConnectingPlayerSessionData(clientId, connectionPayload.playerId,
113-
new SessionPlayerData(clientId, connectionPayload.playerName, new NetworkGuid(), 0, true));
114-
115-
// connection approval will create a player object for you
116-
response.Approved = true;
117-
response.CreatePlayerObject = true;
118-
response.Position = Vector3.zero;
119-
response.Rotation = Quaternion.identity;
120-
return;
121-
}
122-
123-
// In order for clients to not just get disconnected with no feedback, the server needs to tell the client why it disconnected it.
124-
// This could happen after an auth check on a service or because of gameplay reasons (server full, wrong build version, etc)
125-
// Since network objects haven't synced yet (still in the approval process), we need to send a custom message to clients, wait for
126-
// UTP to update a frame and flush that message, then give our response to NetworkManager's connection approval process, with a denied approval.
127-
IEnumerator WaitToDenyApproval()
128-
{
129-
response.Pending = true; // give some time for server to send connection status message to clients
130-
response.Approved = false;
131-
ConnectionManager.SendServerToClientSetDisconnectReason(clientId, gameReturnStatus);
132-
yield return null; // wait a frame so UTP can flush it's messages on next update
133-
response.Pending = false; // connection approval process can be finished.
134-
}
135-
136-
ConnectionManager.SendServerToClientSetDisconnectReason(clientId, gameReturnStatus);
137-
m_ConnectionManager.StartCoroutine(WaitToDenyApproval());
138-
if (m_LobbyServiceFacade.CurrentUnityLobby != null)
139-
{
140-
m_LobbyServiceFacade.RemovePlayerFromLobbyAsync(connectionPayload.playerId, m_LobbyServiceFacade.CurrentUnityLobby.Id);
141-
}
27+
yield return null;
28+
m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
14229
}
14330

144-
ConnectStatus GetConnectStatus(ConnectionPayload connectionPayload)
31+
public override void OnClientDisconnect(ulong clientId)
14532
{
146-
if (m_ConnectionManager.NetworkManager.ConnectedClientsIds.Count >= m_ConnectionManager.MaxConnectedPlayers)
33+
if (clientId == m_ConnectionManager.NetworkManager.LocalClientId)
14734
{
148-
return ConnectStatus.ServerFull;
35+
m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
14936
}
150-
151-
if (connectionPayload.isDebug != Debug.isDebugBuild)
37+
else
15238
{
153-
return ConnectStatus.IncompatibleBuildType;
39+
base.OnClientDisconnect(clientId);
15440
}
155-
156-
return SessionManager<SessionPlayerData>.Instance.IsDuplicateConnection(connectionPayload.playerId) ?
157-
ConnectStatus.LoggedInAgain : ConnectStatus.Success;
158-
}
159-
160-
IEnumerator WaitToShutdown()
161-
{
162-
yield return null;
163-
m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
16441
}
16542
}
16643
}

0 commit comments

Comments
 (0)