forked from Unity-Technologies/com.unity.netcode.gameobjects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkConnectionManager.cs
1639 lines (1460 loc) · 74 KB
/
NetworkConnectionManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Profiling;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// The connection event type set within <see cref="ConnectionEventData"/> to signify the type of connection event notification received.
/// </summary>
/// <remarks>
/// <see cref="ConnectionEventData"/> is returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
/// <see cref="ClientConnected"/> and <see cref="ClientDisconnected"/> event types occur on the client-side of the newly connected client and on the server-side. <br />
/// <see cref="PeerConnected"/> and <see cref="PeerDisconnected"/> event types occur on connected clients to notify that a new client (peer) has joined/connected.
/// </remarks>
public enum ConnectionEvent
{
/// <summary>
/// This event is set on the client-side of the newly connected client and on the server-side.<br />
/// </summary>
/// <remarks>
/// On the newly connected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
/// On the server side, the <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
/// </remarks>
ClientConnected,
/// <summary>
/// This event is set on clients that are already connected to the session.
/// </summary>
/// <remarks>
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
/// </remarks>
PeerConnected,
/// <summary>
/// This event is set on the client-side of the client that disconnected client and on the server-side.
/// </summary>
/// <remarks>
/// On the disconnected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
/// On the server side, this will be the ID of the client that disconnected.
/// </remarks>
ClientDisconnected,
/// <summary>
/// This event is set on clients that are already connected to the session.
/// </summary>
/// <remarks>
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just disconnected.
/// </remarks>
PeerDisconnected
}
/// <summary>
/// Returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
/// </summary>
/// <remarks>
/// See <see cref="ConnectionEvent"/> for more details on the types of connection events received.
/// </remarks>
public struct ConnectionEventData
{
/// <summary>
/// The type of connection event that occurred
/// </summary>
public ConnectionEvent EventType;
/// <summary>
/// The client ID for the client that just connected
/// For the <see cref="ConnectionEvent.ClientConnected"/> and <see cref="ConnectionEvent.ClientDisconnected"/>
/// events on the client side, this will be LocalClientId.
/// On the server side, this will be the ID of the client that just connected.
///
/// For the <see cref="ConnectionEvent.PeerConnected"/> and <see cref="ConnectionEvent.PeerDisconnected"/>
/// events on the client side, this will be the client ID assigned by the server to the remote peer.
/// </summary>
public ulong ClientId;
/// <summary>
/// This is only populated in <see cref="ConnectionEvent.ClientConnected"/> on the client side, and
/// contains the list of other peers who were present before you connected. In all other situations,
/// this array will be uninitialized.
/// </summary>
public NativeArray<ulong> PeerClientIds;
}
/// <summary>
/// The NGO connection manager handles:
/// - Client Connections
/// - Client Approval
/// - Processing <see cref="NetworkEvent"/>s.
/// - Client Disconnection
/// </summary>
public sealed class NetworkConnectionManager
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
private static ProfilerMarker s_TransportPollMarker = new ProfilerMarker($"{nameof(NetworkManager)}.TransportPoll");
private static ProfilerMarker s_TransportConnect = new ProfilerMarker($"{nameof(NetworkManager)}.TransportConnect");
private static ProfilerMarker s_HandleIncomingData = new ProfilerMarker($"{nameof(NetworkManager)}.{nameof(NetworkMessageManager.HandleIncomingData)}");
private static ProfilerMarker s_TransportDisconnect = new ProfilerMarker($"{nameof(NetworkManager)}.TransportDisconnect");
#endif
/// <summary>
/// When disconnected from the server, the server may send a reason. If a reason was sent, this property will
/// tell client code what the reason was. It should be queried after the OnClientDisconnectCallback is called
/// </summary>
public string DisconnectReason { get; internal set; }
/// <summary>
/// The callback to invoke once a client connects. This callback is only ran on the server and on the local client that connects.
/// </summary>
public event Action<ulong> OnClientConnectedCallback = null;
/// <summary>
/// The callback to invoke when a client disconnects. This callback is only ran on the server and on the local client that disconnects.
/// </summary>
public event Action<ulong> OnClientDisconnectCallback = null;
/// <summary>
/// The callback to invoke once a peer connects. This callback is only ran on the server and on the local client that connects.
/// </summary>
public event Action<NetworkManager, ConnectionEventData> OnConnectionEvent = null;
internal void InvokeOnClientConnectedCallback(ulong clientId)
{
try
{
OnClientConnectedCallback?.Invoke(clientId);
}
catch (Exception exception)
{
Debug.LogException(exception);
}
if (!NetworkManager.IsServer)
{
var peerClientIds = new NativeArray<ulong>(Math.Max(NetworkManager.ConnectedClientsIds.Count - 1, 0), Allocator.Temp);
// `using var peerClientIds` or `using(peerClientIds)` renders it immutable...
using var sentinel = peerClientIds;
var idx = 0;
foreach (var peerId in NetworkManager.ConnectedClientsIds)
{
if (peerId == NetworkManager.LocalClientId)
{
continue;
}
// This assures if the server has not timed out prior to the client synchronizing that it doesn't exceed the allocated peer count.
if (peerClientIds.Length > idx)
{
peerClientIds[idx] = peerId;
++idx;
}
}
try
{
OnConnectionEvent?.Invoke(NetworkManager, new ConnectionEventData { ClientId = NetworkManager.LocalClientId, EventType = ConnectionEvent.ClientConnected, PeerClientIds = peerClientIds });
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
else
{
try
{
OnConnectionEvent?.Invoke(NetworkManager, new ConnectionEventData { ClientId = clientId, EventType = ConnectionEvent.ClientConnected });
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
}
internal void InvokeOnClientDisconnectCallback(ulong clientId)
{
try
{
OnClientDisconnectCallback?.Invoke(clientId);
}
catch (Exception exception)
{
Debug.LogException(exception);
}
try
{
OnConnectionEvent?.Invoke(NetworkManager, new ConnectionEventData { ClientId = clientId, EventType = ConnectionEvent.ClientDisconnected });
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
internal void InvokeOnPeerConnectedCallback(ulong clientId)
{
try
{
OnConnectionEvent?.Invoke(NetworkManager, new ConnectionEventData { ClientId = clientId, EventType = ConnectionEvent.PeerConnected });
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
internal void InvokeOnPeerDisconnectedCallback(ulong clientId)
{
try
{
OnConnectionEvent?.Invoke(NetworkManager, new ConnectionEventData { ClientId = clientId, EventType = ConnectionEvent.PeerDisconnected });
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
/// <summary>
/// The callback to invoke if the <see cref="NetworkTransport"/> fails.
/// </summary>
/// <remarks>
/// A failure of the transport is always followed by the <see cref="NetworkManager"/> shutting down. Recovering
/// from a transport failure would normally entail reconfiguring the transport (e.g. re-authenticating, or
/// recreating a new service allocation depending on the transport) and restarting the client/server/host.
/// </remarks>
public event Action OnTransportFailure;
/// <summary>
/// Is true when a server or host is listening for connections.
/// Is true when a client is connecting or connected to a network session.
/// Is false when not listening, connecting, or connected.
/// </summary>
public bool IsListening { get; internal set; }
internal NetworkManager NetworkManager;
internal NetworkMessageManager MessageManager;
internal NetworkClient LocalClient = new NetworkClient();
internal Dictionary<ulong, NetworkManager.ConnectionApprovalResponse> ClientsToApprove = new Dictionary<ulong, NetworkManager.ConnectionApprovalResponse>();
internal Dictionary<ulong, NetworkClient> ConnectedClients = new Dictionary<ulong, NetworkClient>();
internal Dictionary<ulong, ulong> ClientIdToTransportIdMap = new Dictionary<ulong, ulong>();
internal Dictionary<ulong, ulong> TransportIdToClientIdMap = new Dictionary<ulong, ulong>();
internal List<NetworkClient> ConnectedClientsList = new List<NetworkClient>();
internal List<ulong> ConnectedClientIds = new List<ulong>();
internal Action<NetworkManager.ConnectionApprovalRequest, NetworkManager.ConnectionApprovalResponse> ConnectionApprovalCallback;
/// <summary>
/// Use <see cref="AddPendingClient(ulong)"/> and <see cref="RemovePendingClient(ulong)"/> to add or remove
/// Use <see cref="PendingClients"/> to internally access the pending client dictionary
/// </summary>
private Dictionary<ulong, PendingClient> m_PendingClients = new Dictionary<ulong, PendingClient>();
internal IReadOnlyDictionary<ulong, PendingClient> PendingClients => m_PendingClients;
internal Coroutine LocalClientApprovalCoroutine;
/// <summary>
/// Client-Side:
/// Starts the client-side approval timeout coroutine
/// </summary>
/// <param name="clientId"></param>
internal void StartClientApprovalCoroutine(ulong clientId)
{
LocalClientApprovalCoroutine = NetworkManager.StartCoroutine(ApprovalTimeout(clientId));
}
/// <summary>
/// Client-Side:
/// Stops the client-side approval timeout when it is approved.
/// <see cref="ConnectionApprovedMessage.Handle(ref NetworkContext)"/>
/// </summary>
internal void StopClientApprovalCoroutine()
{
if (LocalClientApprovalCoroutine != null)
{
NetworkManager.StopCoroutine(LocalClientApprovalCoroutine);
LocalClientApprovalCoroutine = null;
}
}
/// <summary>
/// Server-Side:
/// Handles the issue with populating NetworkManager.PendingClients
/// </summary>
internal void AddPendingClient(ulong clientId)
{
m_PendingClients.Add(clientId, new PendingClient()
{
ClientId = clientId,
ConnectionState = PendingClient.State.PendingConnection,
ApprovalCoroutine = NetworkManager.StartCoroutine(ApprovalTimeout(clientId))
});
NetworkManager.PendingClients.Add(clientId, PendingClients[clientId]);
}
/// <summary>
/// Server-Side:
/// Handles the issue with depopulating NetworkManager.PendingClients
/// </summary>
internal void RemovePendingClient(ulong clientId)
{
if (m_PendingClients.ContainsKey(clientId) && m_PendingClients[clientId].ApprovalCoroutine != null)
{
NetworkManager.StopCoroutine(m_PendingClients[clientId].ApprovalCoroutine);
}
m_PendingClients.Remove(clientId);
NetworkManager.PendingClients.Remove(clientId);
}
/// <summary>
/// Used to generate client identifiers
/// </summary>
private ulong m_NextClientId = 1;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ulong TransportIdToClientId(ulong transportId)
{
if (transportId == GetServerTransportId())
{
return NetworkManager.ServerClientId;
}
if (TransportIdToClientIdMap.TryGetValue(transportId, out var clientId))
{
return clientId;
}
if (NetworkLog.CurrentLogLevel == LogLevel.Developer)
{
NetworkLog.LogWarning($"Trying to get the NGO client ID map for the transport ID ({transportId}) but did not find the map entry! Returning default transport ID value.");
}
return default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ulong ClientIdToTransportId(ulong clientId)
{
if (clientId == NetworkManager.ServerClientId)
{
return GetServerTransportId();
}
if (ClientIdToTransportIdMap.TryGetValue(clientId, out var transportClientId))
{
return transportClientId;
}
if (NetworkLog.CurrentLogLevel == LogLevel.Developer)
{
NetworkLog.LogWarning($"Trying to get the transport client ID map for the NGO client ID ({clientId}) but did not find the map entry! Returning default transport ID value.");
}
return default;
}
/// <summary>
/// Gets the networkId of the server
/// </summary>
internal ulong ServerTransportId => GetServerTransportId();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ulong GetServerTransportId()
{
if (NetworkManager != null)
{
var transport = NetworkManager.NetworkConfig.NetworkTransport;
if (transport != null)
{
return transport.ServerClientId;
}
throw new NullReferenceException($"The transport in the active {nameof(NetworkConfig)} is null");
}
throw new Exception($"There is no {nameof(NetworkManager)} assigned to this instance!");
}
/// <summary>
/// Handles cleaning up the transport id/client id tables after receiving a disconnect event from transport
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ulong TransportIdCleanUp(ulong transportId)
{
// This check is for clients that attempted to connect but failed.
// When this happens, the client will not have an entry within the m_TransportIdToClientIdMap or m_ClientIdToTransportIdMap lookup tables so we exit early and just return 0 to be used for the disconnect event.
if (!LocalClient.IsServer && !TransportIdToClientIdMap.ContainsKey(transportId))
{
return NetworkManager.LocalClientId;
}
var clientId = TransportIdToClientId(transportId);
TransportIdToClientIdMap.Remove(transportId);
ClientIdToTransportIdMap.Remove(clientId);
return clientId;
}
internal void PollAndHandleNetworkEvents()
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportPollMarker.Begin();
#endif
NetworkEvent networkEvent;
do
{
networkEvent = NetworkManager.NetworkConfig.NetworkTransport.PollEvent(out ulong transportClientId, out ArraySegment<byte> payload, out float receiveTime);
HandleNetworkEvent(networkEvent, transportClientId, payload, receiveTime);
if (networkEvent == NetworkEvent.Disconnect || networkEvent == NetworkEvent.TransportFailure)
{
break;
}
// Only do another iteration if: there are no more messages AND (there is no limit to max events or we have processed less than the maximum)
} while (NetworkManager.IsListening && networkEvent != NetworkEvent.Nothing);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportPollMarker.End();
#endif
}
/// <summary>
/// Event driven NetworkTransports (like UnityTransport) NetworkEvent handling
/// </summary>
/// <remarks>
/// Polling NetworkTransports invoke this directly
/// </remarks>
internal void HandleNetworkEvent(NetworkEvent networkEvent, ulong transportClientId, ArraySegment<byte> payload, float receiveTime)
{
switch (networkEvent)
{
case NetworkEvent.Connect:
ConnectEventHandler(transportClientId);
break;
case NetworkEvent.Data:
DataEventHandler(transportClientId, ref payload, receiveTime);
break;
case NetworkEvent.Disconnect:
DisconnectEventHandler(transportClientId);
break;
case NetworkEvent.TransportFailure:
TransportFailureEventHandler();
break;
}
}
/// <summary>
/// Handles a <see cref="NetworkEvent.Connect"/> event.
/// </summary>
internal void ConnectEventHandler(ulong transportClientId)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportConnect.Begin();
#endif
// Assumptions:
// - When server receives a connection, it *must be* a client
// - When client receives one, it *must be* the server
// Client's can't connect to or talk to other clients.
// Server is a sentinel so only one exists, if we are server, we can't be connecting to it.
var clientId = transportClientId;
if (LocalClient.IsServer)
{
clientId = m_NextClientId++;
}
else
{
clientId = NetworkManager.ServerClientId;
}
ClientIdToTransportIdMap[clientId] = transportClientId;
TransportIdToClientIdMap[transportClientId] = clientId;
MessageManager.ClientConnected(clientId);
if (LocalClient.IsServer)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
var hostServer = NetworkManager.IsHost ? "Host" : "Server";
NetworkLog.LogInfo($"[{hostServer}-Side] Transport connection established with pending Client-{clientId}.");
}
AddPendingClient(clientId);
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
var serverOrService = NetworkManager.DistributedAuthorityMode ? NetworkManager.CMBServiceConnection ? "service" : "DAHost" : "server";
NetworkLog.LogInfo($"[Approval Pending][Client] Transport connection with {serverOrService} established! Awaiting connection approval...");
}
SendConnectionRequest();
StartClientApprovalCoroutine(clientId);
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportConnect.End();
#endif
}
/// <summary>
/// Handles a <see cref="NetworkEvent.Data"/> event.
/// </summary>
internal void DataEventHandler(ulong transportClientId, ref ArraySegment<byte> payload, float receiveTime)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleIncomingData.Begin();
#endif
var clientId = TransportIdToClientId(transportClientId);
MessageManager.HandleIncomingData(clientId, payload, receiveTime);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleIncomingData.End();
#endif
}
/// <summary>
/// Handles a <see cref="NetworkEvent.Disconnect"/> event.
/// </summary>
internal void DisconnectEventHandler(ulong transportClientId)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportDisconnect.Begin();
#endif
var clientId = TransportIdCleanUp(transportClientId);
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
NetworkLog.LogInfo($"Disconnect Event From {clientId}");
}
// If we are a client and we have gotten the ServerClientId back, then use our assigned local id as the client that was
// disconnected (either the user disconnected or the server disconnected, but the client that disconnected is the LocalClientId)
if (!NetworkManager.IsServer && clientId == NetworkManager.ServerClientId)
{
clientId = NetworkManager.LocalClientId;
}
// Process the incoming message queue so that we get everything from the server disconnecting us or, if we are the server, so we got everything from that client.
MessageManager.ProcessIncomingMessageQueue();
if (LocalClient.IsServer)
{
// We need to process the disconnection before notifying
OnClientDisconnectFromServer(clientId);
// Now notify the client has disconnected
InvokeOnClientDisconnectCallback(clientId);
if (LocalClient.IsHost)
{
InvokeOnPeerDisconnectedCallback(clientId);
}
}
else
{
// Notify local client of disconnection
InvokeOnClientDisconnectCallback(clientId);
// As long as we are not in the middle of a shutdown
if (!NetworkManager.ShutdownInProgress)
{
// We must pass true here and not process any sends messages as we are no longer connected.
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
// as the client ID is no longer valid.
NetworkManager.Shutdown(true);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportDisconnect.End();
#endif
}
/// <summary>
/// Handles a <see cref="NetworkEvent.TransportFailure"/> event.
/// </summary>
internal void TransportFailureEventHandler(bool duringStart = false)
{
var clientSeverOrHost = LocalClient.IsServer ? LocalClient.IsHost ? "Host" : "Server" : "Client";
var whenFailed = duringStart ? "start failure" : "failure";
NetworkLog.LogError($"{clientSeverOrHost} is shutting down due to network transport {whenFailed} of {NetworkManager.NetworkConfig.NetworkTransport.GetType().Name}!");
OnTransportFailure?.Invoke();
// If we had a transport failure when trying to start, reset the local client roles and directly invoke the internal shutdown.
if (duringStart)
{
LocalClient.SetRole(false, false);
NetworkManager.ShutdownInternal();
}
else
{
// Otherwise, stop processing messages and shutdown the normal way
NetworkManager.Shutdown(true);
}
}
/// <summary>
/// Client-Side:
/// Upon transport connecting, the client will send a connection request
/// </summary>
private void SendConnectionRequest()
{
var message = new ConnectionRequestMessage
{
DistributedAuthority = NetworkManager.DistributedAuthorityMode,
// Since only a remote client will send a connection request, we should always force the rebuilding of the NetworkConfig hash value
ConfigHash = NetworkManager.NetworkConfig.GetConfig(false),
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
ConnectionData = NetworkManager.NetworkConfig.ConnectionData,
MessageVersions = new NativeArray<MessageVersionData>(MessageManager.MessageHandlers.Length, Allocator.Temp)
};
if (NetworkManager.DistributedAuthorityMode)
{
message.ClientConfig.SessionConfig = NetworkManager.SessionConfig;
message.ClientConfig.TickRate = NetworkManager.NetworkConfig.TickRate;
message.ClientConfig.EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement;
}
for (int index = 0; index < MessageManager.MessageHandlers.Length; index++)
{
if (MessageManager.MessageTypes[index] != null)
{
var type = MessageManager.MessageTypes[index];
message.MessageVersions[index] = new MessageVersionData
{
Hash = XXHash.Hash32(type.FullName),
Version = MessageManager.GetLocalVersion(type)
};
}
}
SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId);
message.MessageVersions.Dispose();
}
/// <summary>
/// Approval time out coroutine
/// </summary>
private IEnumerator ApprovalTimeout(ulong clientId)
{
var timeStarted = LocalClient.IsServer ? NetworkManager.LocalTime.TimeAsFloat : NetworkManager.RealTimeProvider.RealTimeSinceStartup;
var timedOut = false;
var connectionApproved = false;
var connectionNotApproved = false;
var timeoutMarker = timeStarted + NetworkManager.NetworkConfig.ClientConnectionBufferTimeout;
while (NetworkManager.IsListening && !NetworkManager.ShutdownInProgress && !timedOut && !connectionApproved)
{
yield return null;
// Check if we timed out
timedOut = timeoutMarker < (LocalClient.IsServer ? NetworkManager.LocalTime.TimeAsFloat : NetworkManager.RealTimeProvider.RealTimeSinceStartup);
if (LocalClient.IsServer)
{
// When the client is no longer in the pending clients list and is in the connected clients list it has been approved
connectionApproved = !PendingClients.ContainsKey(clientId) && ConnectedClients.ContainsKey(clientId);
// For the server side, if the client is in neither list then it was declined or the client disconnected
connectionNotApproved = !PendingClients.ContainsKey(clientId) && !ConnectedClients.ContainsKey(clientId);
}
else
{
connectionApproved = NetworkManager.LocalClient.IsApproved;
}
}
// Exit coroutine if we are no longer listening or a shutdown is in progress (client or server)
if (!NetworkManager.IsListening || NetworkManager.ShutdownInProgress)
{
yield break;
}
// If the client timed out or was not approved
if (timedOut || connectionNotApproved)
{
// Timeout
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
if (timedOut)
{
if (LocalClient.IsServer)
{
// Log a warning that the transport detected a connection but then did not receive a follow up connection request message.
// (hacking or something happened to the server's network connection)
NetworkLog.LogWarning($"Server detected a transport connection from Client-{clientId}, but timed out waiting for the connection request message.");
}
else
{
// We only provide informational logging for the client side
NetworkLog.LogInfo("Timed out waiting for the server to approve the connection request.");
}
}
else if (connectionNotApproved)
{
NetworkLog.LogInfo($"Client-{clientId} was either denied approval or disconnected while being approved.");
}
}
if (LocalClient.IsServer)
{
DisconnectClient(clientId);
}
else
{
NetworkManager.Shutdown(true);
}
}
}
/// <summary>
/// Server-Side:
/// Handles approval while processing a client connection request
/// </summary>
internal void ApproveConnection(ref ConnectionRequestMessage connectionRequestMessage, ref NetworkContext context)
{
// Note: Delegate creation allocates.
// Note: ToArray() also allocates. :(
var response = new NetworkManager.ConnectionApprovalResponse();
ClientsToApprove[context.SenderId] = response;
ConnectionApprovalCallback(
new NetworkManager.ConnectionApprovalRequest
{
Payload = connectionRequestMessage.ConnectionData,
ClientNetworkId = context.SenderId
}, response);
}
/// <summary>
/// Server-Side:
/// Processes pending approvals and removes any stale pending clients
/// </summary>
internal void ProcessPendingApprovals()
{
List<ulong> senders = null;
foreach (var responsePair in ClientsToApprove)
{
var response = responsePair.Value;
var senderId = responsePair.Key;
if (!response.Pending)
{
try
{
HandleConnectionApproval(senderId, response);
senders ??= new List<ulong>();
senders.Add(senderId);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}
if (senders != null)
{
foreach (var sender in senders)
{
ClientsToApprove.Remove(sender);
}
}
}
/// <summary>
/// Adding this because message hooks cannot happen fast enough under certain scenarios
/// where the message is sent and responded to before the hook is in place.
/// </summary>
internal bool MockSkippingApproval;
/// <summary>
/// Server Side: Handles the approval of a client
/// </summary>
/// <remarks>
/// This will spawn the player prefab as well as start client synchronization if <see cref="NetworkConfig.EnableSceneManagement"/> is enabled
/// </remarks>
internal void HandleConnectionApproval(ulong ownerClientId, NetworkManager.ConnectionApprovalResponse response)
{
LocalClient.IsApproved = response.Approved;
if (response.Approved)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
NetworkLog.LogInfo($"[Server-Side] Pending Client-{ownerClientId} connection approved!");
}
// The client was approved, stop the server-side approval time out coroutine
RemovePendingClient(ownerClientId);
var client = AddClient(ownerClientId);
// Server-side spawning (only if there is a prefab hash or player prefab provided)
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && (response.PlayerPrefabHash.HasValue || NetworkManager.NetworkConfig.PlayerPrefab != null))
{
var instantiationPayloadWriter = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(new FastBufferWriter(0,Allocator.Temp)));
var playerObject = response.PlayerPrefabHash.HasValue ? NetworkManager.SpawnManager.GetNetworkObjectToSpawn(response.PlayerPrefabHash.Value, ownerClientId, ref instantiationPayloadWriter, response.Position ?? null, response.Rotation ?? null)
: NetworkManager.SpawnManager.GetNetworkObjectToSpawn(NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash, ownerClientId, ref instantiationPayloadWriter, response.Position ?? null, response.Rotation ?? null);
// Spawn the player NetworkObject locally
NetworkManager.SpawnManager.SpawnNetworkObjectLocally(
playerObject,
NetworkManager.SpawnManager.GetNetworkObjectId(),
sceneObject: false,
playerObject: true,
ownerClientId,
destroyWithScene: false);
client.AssignPlayerObject(ref playerObject);
}
// Server doesn't send itself the connection approved message
if (ownerClientId != NetworkManager.ServerClientId)
{
var message = new ConnectionApprovedMessage
{
OwnerClientId = ownerClientId,
NetworkTick = NetworkManager.LocalTime.Tick,
IsDistributedAuthority = NetworkManager.DistributedAuthorityMode,
ConnectedClientIds = new NativeArray<ulong>(ConnectedClientIds.Count, Allocator.Temp)
};
var i = 0;
foreach (var clientId in ConnectedClientIds)
{
message.ConnectedClientIds[i] = clientId;
++i;
}
if (!NetworkManager.NetworkConfig.EnableSceneManagement)
{
// Update the observed spawned NetworkObjects for the newly connected player when scene management is disabled
NetworkManager.SpawnManager.UpdateObservedNetworkObjects(ownerClientId);
if (NetworkManager.SpawnManager.SpawnedObjectsList.Count != 0)
{
message.SpawnedObjectsList = NetworkManager.SpawnManager.SpawnedObjectsList;
}
}
message.MessageVersions = new NativeArray<MessageVersionData>(MessageManager.MessageHandlers.Length, Allocator.Temp);
for (int index = 0; index < MessageManager.MessageHandlers.Length; index++)
{
if (MessageManager.MessageTypes[index] != null)
{
var type = MessageManager.MessageTypes[index];
message.MessageVersions[index] = new MessageVersionData
{
Hash = XXHash.Hash32(type.FullName),
Version = MessageManager.GetLocalVersion(type)
};
}
}
if (!MockSkippingApproval)
{
SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ownerClientId);
}
else
{
NetworkLog.LogInfo("Mocking server not responding with connection approved...");
}
message.MessageVersions.Dispose();
message.ConnectedClientIds.Dispose();
if (MockSkippingApproval)
{
return;
}
// If scene management is disabled, then we are done and notify the local host-server the client is connected
if (!NetworkManager.NetworkConfig.EnableSceneManagement)
{
NetworkManager.ConnectedClients[ownerClientId].IsConnected = true;
InvokeOnClientConnectedCallback(ownerClientId);
if (LocalClient.IsHost)
{
InvokeOnPeerConnectedCallback(ownerClientId);
}
NetworkManager.SpawnManager.DistributeNetworkObjects(ownerClientId);
}
else // Otherwise, let NetworkSceneManager handle the initial scene and NetworkObject synchronization
{
if (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner)
{
NetworkManager.SceneManager.SynchronizeNetworkObjects(ownerClientId);
}
else if (!NetworkManager.DistributedAuthorityMode)
{
NetworkManager.SceneManager.SynchronizeNetworkObjects(ownerClientId);
}
}
}
else // Server just adds itself as an observer to all spawned NetworkObjects
{
LocalClient = client;
NetworkManager.SpawnManager.UpdateObservedNetworkObjects(ownerClientId);
LocalClient.IsConnected = true;
// If running mock service, then set the instance as the default session owner
if (NetworkManager.DistributedAuthorityMode && NetworkManager.DAHost)
{
NetworkManager.SetSessionOwner(NetworkManager.LocalClientId);
NetworkManager.SceneManager.InitializeScenesLoaded();
}
if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide)
{
CreateAndSpawnPlayer(ownerClientId);
}
}
// Exit early if no player object was spawned
if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null))
{
return;
}
// Players are always spawned by their respective client, exit early. (DAHost mode anyway, CMB Service will never spawn player prefab)
if (NetworkManager.DistributedAuthorityMode)
{
return;
}
// Separating this into a contained function call for potential further future separation of when this notification is sent.
ApprovedPlayerSpawn(ownerClientId, response.PlayerPrefabHash ?? NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash);
}
else
{
if (!string.IsNullOrEmpty(response.Reason))
{
var disconnectReason = new DisconnectReasonMessage
{
Reason = response.Reason
};
SendMessage(ref disconnectReason, NetworkDelivery.Reliable, ownerClientId);
MessageManager.ProcessSendQueues();
}
DisconnectRemoteClient(ownerClientId);
}
}
/// <summary>
/// Client-Side Spawning in distributed authority mode uses this to spawn the player.
/// </summary>
internal void CreateAndSpawnPlayer(ulong ownerId)
{
if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide)
{
var playerPrefab = NetworkManager.FetchLocalPlayerPrefabToSpawn();
if (playerPrefab != null)
{
var globalObjectIdHash = playerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash;
var instantiationPayloadWriter = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(new FastBufferWriter(0, Allocator.Temp)));
var networkObject = NetworkManager.SpawnManager.GetNetworkObjectToSpawn(globalObjectIdHash, ownerId, ref instantiationPayloadWriter, playerPrefab.transform.position, playerPrefab.transform.rotation);
networkObject.IsSceneObject = false;
networkObject.SpawnAsPlayerObject(ownerId, networkObject.DestroyWithScene);
}
}
}
/// <summary>
/// Spawns the newly approved player
/// </summary>
/// <param name="clientId">new player client identifier</param>
/// <param name="playerPrefabHash">the prefab GlobalObjectIdHash value for this player</param>
internal void ApprovedPlayerSpawn(ulong clientId, uint playerPrefabHash)
{
foreach (var clientPair in ConnectedClients)
{
if (clientPair.Key == clientId ||
clientPair.Key == NetworkManager.ServerClientId || // Server already spawned it
ConnectedClients[clientId].PlayerObject == null ||
!ConnectedClients[clientId].PlayerObject.Observers.Contains(clientPair.Key))
{
continue; //The new client.
}
var message = new CreateObjectMessage
{
ObjectInfo = ConnectedClients[clientId].PlayerObject.GetMessageSceneObject(clientPair.Key),
IncludesSerializedObject = true,
};
message.ObjectInfo.Hash = playerPrefabHash;
message.ObjectInfo.IsSceneObject = false;
message.ObjectInfo.HasParent = false;
message.ObjectInfo.IsPlayerObject = true;
message.ObjectInfo.OwnerClientId = clientId;
var size = SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, clientPair.Key);
NetworkManager.NetworkMetrics.TrackObjectSpawnSent(clientPair.Key, ConnectedClients[clientId].PlayerObject, size);
}
}
/// <summary>
/// Server-Side:
/// Creates a new <see cref="NetworkClient"/> and handles updating the associated
/// connected clients lists.
/// </summary>
internal NetworkClient AddClient(ulong clientId)