-
Notifications
You must be signed in to change notification settings - Fork 429
/
NetworkingManager.cs
1646 lines (1446 loc) · 73.6 KB
/
NetworkingManager.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.ComponentModel;
using System.Diagnostics;
using UnityEngine;
using System.Linq;
using MLAPI.Logging;
using UnityEngine.SceneManagement;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using MLAPI.Configuration;
using MLAPI.Security;
using MLAPI.Internal;
using MLAPI.Profiling;
using MLAPI.Serialization;
using MLAPI.Transports;
using BitStream = MLAPI.Serialization.BitStream;
using MLAPI.Connection;
using MLAPI.LagCompensation;
using MLAPI.Messaging;
using MLAPI.SceneManagement;
using MLAPI.Serialization.Pooled;
using MLAPI.Spawning;
using static MLAPI.Messaging.CustomMessagingManager;
using MLAPI.Exceptions;
using MLAPI.Transports.Tasks;
using MLAPI.Messaging.Buffering;
using Unity.Profiling;
namespace MLAPI
{
/// <summary>
/// The main component of the library
/// </summary>
[AddComponentMenu("MLAPI/NetworkingManager", -100)]
public class NetworkingManager : MonoBehaviour, INetworkUpdateSystem
{
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#if UNITY_2020_2_OR_NEWER
// RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<uint, Action<NetworkedBehaviour, BitSerializer, __RpcParams>> __ntable = new Dictionary<uint, Action<NetworkedBehaviour, BitSerializer, __RpcParams>>();
#else
[Obsolete("Please do not use, will no longer be exposed in the future versions (framework internal)")]
public static readonly Dictionary<uint, Action<NetworkedBehaviour, BitSerializer, __RpcParams>> __ntable = new Dictionary<uint, Action<NetworkedBehaviour, BitSerializer, __RpcParams>>();
#endif
#if DEVELOPMENT_BUILD || UNITY_EDITOR
static ProfilerMarker s_EventTick = new ProfilerMarker("Event");
static ProfilerMarker s_ReceiveTick = new ProfilerMarker("Receive");
static ProfilerMarker s_SyncTime = new ProfilerMarker("SyncTime");
static ProfilerMarker s_TransportConnect = new ProfilerMarker("TransportConnect");
static ProfilerMarker s_HandleIncomingData = new ProfilerMarker("HandleIncomingData");
static ProfilerMarker s_TransportDisconnect = new ProfilerMarker("TransportDisconnect");
static ProfilerMarker s_MLAPIServerRPC = new ProfilerMarker("MLAPIServerRPC");
static ProfilerMarker s_MLAPIServerRPCQueued = new ProfilerMarker("MLAPIServerRPCQueued");
static ProfilerMarker s_MLAPIClientRPC = new ProfilerMarker("MLAPIClientRPC");
static ProfilerMarker s_MLAPIClientRPCQueued = new ProfilerMarker("MLAPIClientRPCQueued");
static ProfilerMarker s_MLAPIServerSTDRPC = new ProfilerMarker("MLAPIServerSTDRPC");
static ProfilerMarker s_MLAPIServerSTDRPCQueued = new ProfilerMarker("MLAPIServerSTDRPCQueued");
static ProfilerMarker s_MLAPIClientSTDRPC = new ProfilerMarker("MLAPIClientSTDRPC");
static ProfilerMarker s_MLAPIClientSTDRPCQueued = new ProfilerMarker("MLAPIClientSTDRPCQueued");
static ProfilerMarker s_InvokeRPC = new ProfilerMarker("InvokeRPC");
#endif
public RpcQueueContainer rpcQueueContainer { get; private set; }
/// <summary>
/// A synchronized time, represents the time in seconds since the server application started. Is replicated across all clients
/// </summary>
public float NetworkTime => Time.unscaledTime + currentNetworkTimeOffset;
private float networkTimeOffset;
private float currentNetworkTimeOffset;
/// <summary>
/// Gets or sets if the NetworkingManager should be marked as DontDestroyOnLoad
/// </summary>
[HideInInspector]
public bool DontDestroy = true;
/// <summary>
/// Gets or sets if the application should be set to run in background
/// </summary>
[HideInInspector]
public bool RunInBackground = true;
/// <summary>
/// The log level to use
/// </summary>
[HideInInspector]
public LogLevel LogLevel = LogLevel.Normal;
/// <summary>
/// The singleton instance of the NetworkingManager
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use Singleton instead", false)]
public static NetworkingManager singleton => Singleton;
/// <summary>
/// The singleton instance of the NetworkingManager
/// </summary>
public static NetworkingManager Singleton { get; private set; }
/// <summary>
/// Gets the networkId of the server
/// </summary>
public ulong ServerClientId => NetworkConfig.NetworkTransport != null ? NetworkConfig.NetworkTransport.ServerClientId : throw new NullReferenceException("The transport in the active NetworkConfig is null");
/// <summary>
/// The clientId the server calls the local client by, only valid for clients
/// </summary>
public ulong LocalClientId
{
get => IsServer ? NetworkConfig.NetworkTransport.ServerClientId : localClientId;
internal set => localClientId = value;
}
private ulong localClientId;
/// <summary>
/// Gets a dictionary of connected clients and their clientId keys. This is only populated on the server.
/// </summary>
public readonly Dictionary<ulong, NetworkedClient> ConnectedClients = new Dictionary<ulong, NetworkedClient>();
/// <summary>
/// Gets a list of connected clients. This is only populated on the server.
/// </summary>
public readonly List<NetworkedClient> ConnectedClientsList = new List<NetworkedClient>();
/// <summary>
/// Gets a dictionary of the clients that have been accepted by the transport but are still pending by the MLAPI. This is only populated on the server.
/// </summary>
public readonly Dictionary<ulong, PendingClient> PendingClients = new Dictionary<ulong, PendingClient>();
/// <summary>
/// Gets Whether or not a server is running
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsServer instead", false)]
public bool isServer => IsServer;
/// <summary>
/// Gets Whether or not a server is running
/// </summary>
public bool IsServer { get; internal set; }
/// <summary>
/// Gets Whether or not a client is running
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsClient instead", false)]
public bool isClient => IsClient;
/// <summary>
/// Gets Whether or not a client is running
/// </summary>
public bool IsClient { get; internal set; }
/// <summary>
/// Gets if we are running as host
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsHost instead", false)]
public bool isHost => IsHost;
/// <summary>
/// Gets if we are running as host
/// </summary>
public bool IsHost => IsServer && IsClient;
/// <summary>
/// Gets Whether or not we are listening for connections
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsListening instead", false)]
public bool isListening => IsListening;
/// <summary>
/// Gets Whether or not we are listening for connections
/// </summary>
public bool IsListening { get; internal set; }
/// <summary>
/// Gets if we are connected as a client
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsConnectedClient instead", false)]
public bool isConnectedClients => IsConnectedClient;
/// <summary>
/// Gets if we are connected as a client
/// </summary>
public bool IsConnectedClient { 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;
internal void InvokeOnClientConnectedCallback(ulong clientId)
{
if (OnClientConnectedCallback != null)
{
OnClientConnectedCallback(clientId);
}
}
/// <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;
internal void InvokeOnClientDisconnectCallback(ulong clientId)
{
if (OnClientDisconnectCallback != null)
{
OnClientDisconnectCallback(clientId);
}
}
/// <summary>
/// The callback to invoke once the server is ready
/// </summary>
public event Action OnServerStarted = null;
/// <summary>
/// Delegate type called when connection has been approved. This only has to be set on the server.
/// </summary>
/// <param name="createPlayerObject">If true, a player object will be created. Otherwise the client will have no object.</param>
/// <param name="playerPrefabHash">The prefabHash to use for the client. If createPlayerObject is false, this is ignored. If playerPrefabHash is null, the default player prefab is used.</param>
/// <param name="approved">Whether or not the client was approved</param>
/// <param name="position">The position to spawn the client at. If null, the prefab position is used.</param>
/// <param name="rotation">The rotation to spawn the client with. If null, the prefab position is used.</param>
public delegate void ConnectionApprovedDelegate(bool createPlayerObject, ulong? playerPrefabHash, bool approved, Vector3? position, Quaternion? rotation);
/// <summary>
/// The callback to invoke during connection approval
/// </summary>
public event Action<byte[], ulong, ConnectionApprovedDelegate> ConnectionApprovalCallback = null;
internal void InvokeConnectionApproval(byte[] payload, ulong clientId, ConnectionApprovedDelegate action)
{
if (ConnectionApprovalCallback != null)
{
ConnectionApprovalCallback(payload, clientId, action);
}
}
/// <summary>
/// The current NetworkingConfiguration
/// </summary>
[HideInInspector]
public NetworkConfig NetworkConfig;
[Obsolete("Use OnUnnamedMessage instead")]
public event UnnamedMessageDelegate OnIncomingCustomMessage;
/// <summary>
/// The current hostname we are connected to, used to validate certificate
/// </summary>
public string ConnectedHostname { get; private set; }
internal byte[] clientAesKey;
internal static event Action OnSingletonReady;
internal void InvokeOnIncomingCustomMessage(ulong clientId, Stream stream)
{
if (OnIncomingCustomMessage != null)
{
OnIncomingCustomMessage(clientId, stream);
}
}
/// <summary>
/// Sends unnamed message to a list of clients
/// </summary>
/// <param name="clientIds">The clients to send to, sends to everyone if null</param>
/// <param name="stream">The message stream containing the data</param>
/// <param name="channel">The channel to send the data on</param>
/// <param name="security">The security settings to apply to the message</param>
[Obsolete("Use CustomMessagingManager.SendUnnamedMessage instead")]
public void SendCustomMessage(List<ulong> clientIds, BitStream stream, Channel channel = Channel.Internal, SecuritySendFlags security = SecuritySendFlags.None)
{
if (!IsServer)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogWarning("Can not send unnamed message to multiple users as a client");
return;
}
InternalMessageSender.Send(MLAPIConstants.MLAPI_UNNAMED_MESSAGE, channel, clientIds, stream, security);
}
/// <summary>
/// Sends a unnamed message to a specific client
/// </summary>
/// <param name="clientId">The client to send the message to</param>
/// <param name="stream">The message stream containing the data</param>
/// <param name="channel">The channel tos end the data on</param>
/// <param name="security">The security settings to apply to the message</param>
[Obsolete("Use CustomMessagingManager.SendUnnamedMessage instead")]
public void SendCustomMessage(ulong clientId, BitStream stream, Channel channel = Channel.Internal, SecuritySendFlags security = SecuritySendFlags.None)
{
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_UNNAMED_MESSAGE, channel, stream, security);
}
private void OnValidate()
{
if (NetworkConfig == null)
return; //May occur when the component is added
if (GetComponentInChildren<NetworkedObject>() != null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("The NetworkingManager cannot be a NetworkedObject. This will lead to weird side effects.");
}
if (!NetworkConfig.RegisteredScenes.Contains(SceneManager.GetActiveScene().name))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("The active scene is not registered as a networked scene. The MLAPI has added it");
NetworkConfig.RegisteredScenes.Add(SceneManager.GetActiveScene().name);
}
for (int i = 0; i < NetworkConfig.NetworkedPrefabs.Count; i++)
{
if (NetworkConfig.NetworkedPrefabs[i] != null && NetworkConfig.NetworkedPrefabs[i].Prefab != null)
{
if (NetworkConfig.NetworkedPrefabs[i].Prefab.GetComponent<NetworkedObject>() == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("The network prefab [" + i + "] does not have a NetworkedObject component");
}
else
{
NetworkConfig.NetworkedPrefabs[i].Prefab.GetComponent<NetworkedObject>().ValidateHash();
}
}
}
// TODO: Show which two prefab generators that collide
HashSet<ulong> hashes = new HashSet<ulong>();
for (int i = 0; i < NetworkConfig.NetworkedPrefabs.Count; i++)
{
if (hashes.Contains(NetworkConfig.NetworkedPrefabs[i].Hash))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
var prefabHashGenerator = NetworkConfig.NetworkedPrefabs[i].Prefab.GetComponent<NetworkedObject>().PrefabHashGenerator;
NetworkLog.LogError($"PrefabHash collision! You have two prefabs with the same hash (PrefabHashGenerator = {prefabHashGenerator}). This is not supported");
}
}
hashes.Add(NetworkConfig.NetworkedPrefabs[i].Hash);
}
int playerPrefabCount = NetworkConfig.NetworkedPrefabs.Count(x => x.PlayerPrefab == true);
if (playerPrefabCount == 0 && !NetworkConfig.ConnectionApproval && NetworkConfig.CreatePlayerPrefab)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("There is no NetworkedPrefab marked as a PlayerPrefab");
}
else if (playerPrefabCount > 1)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Only one networked prefab can be marked as a player prefab");
}
NetworkedPrefab prefab = NetworkConfig.NetworkedPrefabs.FirstOrDefault(x => x.PlayerPrefab == true);
if (prefab == null)
{
NetworkConfig.PlayerPrefabHash = null;
}
else
{
if (NetworkConfig.PlayerPrefabHash == null)
{
NetworkConfig.PlayerPrefabHash = new NullableBoolSerializable();
}
NetworkConfig.PlayerPrefabHash.Value = prefab.Hash;
}
}
private void Init(bool server)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Init()");
LocalClientId = 0;
networkTimeOffset = 0f;
currentNetworkTimeOffset = 0f;
m_LastReceiveTickTime = 0f;
m_LastReceiveTickTime = 0f;
m_EventOvershootCounter = 0f;
PendingClients.Clear();
ConnectedClients.Clear();
ConnectedClientsList.Clear();
SpawnManager.SpawnedObjects.Clear();
SpawnManager.SpawnedObjectsList.Clear();
SpawnManager.releasedNetworkObjectIds.Clear();
SpawnManager.pendingSoftSyncObjects.Clear();
NetworkSceneManager.registeredSceneNames.Clear();
NetworkSceneManager.sceneIndexToString.Clear();
NetworkSceneManager.sceneNameToIndex.Clear();
NetworkSceneManager.sceneSwitchProgresses.Clear();
if (NetworkConfig.NetworkTransport == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("No transport has been selected!");
return;
}
try
{
string pfx = null;
if (NetworkConfig.ServerBase64PfxCertificate != null)
{
pfx = NetworkConfig.ServerBase64PfxCertificate.Trim();
}
if (server && pfx != null && NetworkConfig.EnableEncryption && NetworkConfig.SignKeyExchange && !string.IsNullOrEmpty(pfx))
{
try
{
byte[] decodedPfx = Convert.FromBase64String(pfx);
NetworkConfig.ServerX509Certificate = new X509Certificate2(decodedPfx);
if (!NetworkConfig.ServerX509Certificate.HasPrivateKey)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("The imported PFX file did not have a private key");
}
}
catch (FormatException ex)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Parsing PFX failed: " + ex.ToString());
}
}
}
catch (CryptographicException ex)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Importing of certificate failed: " + ex.ToString());
}
if (NetworkConfig.EnableSceneManagement)
{
NetworkConfig.RegisteredScenes.Sort(StringComparer.Ordinal);
for (int i = 0; i < NetworkConfig.RegisteredScenes.Count; i++)
{
NetworkSceneManager.registeredSceneNames.Add(NetworkConfig.RegisteredScenes[i]);
NetworkSceneManager.sceneIndexToString.Add((uint)i, NetworkConfig.RegisteredScenes[i]);
NetworkSceneManager.sceneNameToIndex.Add(NetworkConfig.RegisteredScenes[i], (uint)i);
}
NetworkSceneManager.SetCurrentSceneIndex();
}
for (int i = 0; i < NetworkConfig.NetworkedPrefabs.Count; i++)
{
if (NetworkConfig.NetworkedPrefabs[i] == null || NetworkConfig.NetworkedPrefabs[i].Prefab == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Networked prefab cannot be null");
}
else if (NetworkConfig.NetworkedPrefabs[i].Prefab.GetComponent<NetworkedObject>() == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Networked prefab is missing a NetworkedObject component");
}
else
{
NetworkConfig.NetworkedPrefabs[i].Prefab.GetComponent<NetworkedObject>().ValidateHash();
}
}
NetworkConfig.NetworkTransport.OnTransportEvent += HandleRawTransportPoll;
NetworkConfig.NetworkTransport.ResetChannelCache();
NetworkConfig.NetworkTransport.Init();
}
/// <summary>
/// Starts a server
/// </summary>
public SocketTasks StartServer()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StartServer()");
if (IsServer || IsClient)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Cannot start server while an instance is already running");
return SocketTask.Fault.AsTasks();
}
if (NetworkConfig.ConnectionApproval)
{
if (ConnectionApprovalCallback == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("No ConnectionApproval callback defined. Connection approval will timeout");
}
}
Init(true);
SocketTasks tasks = NetworkConfig.NetworkTransport.StartServer();
IsServer = true;
IsClient = false;
IsListening = true;
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
if (OnServerStarted != null)
OnServerStarted.Invoke();
return tasks;
}
/// <summary>
/// Starts a client
/// </summary>
public SocketTasks StartClient()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StartClient()");
if (IsServer || IsClient)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Cannot start client while an instance is already running");
return SocketTask.Fault.AsTasks();
}
Init(false);
SocketTasks tasks = NetworkConfig.NetworkTransport.StartClient();
IsServer = false;
IsClient = true;
IsListening = true;
return tasks;
}
/// <summary>
/// Stops the running server
/// </summary>
public void StopServer()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StopServer()");
HashSet<ulong> disconnectedIds = new HashSet<ulong>();
//Don't know if I have to disconnect the clients. I'm assuming the NetworkTransport does all the cleaning on shtudown. But this way the clients get a disconnect message from server (so long it does't get lost)
foreach (KeyValuePair<ulong, NetworkedClient> pair in ConnectedClients)
{
if (!disconnectedIds.Contains(pair.Key))
{
disconnectedIds.Add(pair.Key);
if (pair.Key == NetworkConfig.NetworkTransport.ServerClientId)
continue;
NetworkConfig.NetworkTransport.DisconnectRemoteClient(pair.Key);
}
}
foreach (KeyValuePair<ulong, PendingClient> pair in PendingClients)
{
if(!disconnectedIds.Contains(pair.Key))
{
disconnectedIds.Add(pair.Key);
if (pair.Key == NetworkConfig.NetworkTransport.ServerClientId)
continue;
NetworkConfig.NetworkTransport.DisconnectRemoteClient(pair.Key);
}
}
IsServer = false;
Shutdown();
}
/// <summary>
/// Stops the running host
/// </summary>
public void StopHost()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StopHost()");
IsServer = false;
IsClient = false;
StopServer();
//We don't stop client since we dont actually have a transport connection to our own host. We just handle host messages directly in the MLAPI
}
/// <summary>
/// Stops the running client
/// </summary>
public void StopClient()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StopClient()");
IsClient = false;
NetworkConfig.NetworkTransport.DisconnectLocalClient();
IsConnectedClient = false;
Shutdown();
}
/// <summary>
/// Starts a Host
/// </summary>
public SocketTasks StartHost(Vector3? position = null, Quaternion? rotation = null, bool? createPlayerObject = null, ulong? prefabHash = null, Stream payloadStream = null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StartHost()");
if (IsServer || IsClient)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Cannot start host while an instance is already running");
return SocketTask.Fault.AsTasks();
}
if (NetworkConfig.ConnectionApproval)
{
if (ConnectionApprovalCallback == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("No ConnectionApproval callback defined. Connection approval will timeout");
}
}
Init(true);
SocketTasks tasks = NetworkConfig.NetworkTransport.StartServer();
IsServer = true;
IsClient = true;
IsListening = true;
ulong hostClientId = NetworkConfig.NetworkTransport.ServerClientId;
ConnectedClients.Add(hostClientId, new NetworkedClient()
{
ClientId = hostClientId
});
ConnectedClientsList.Add(ConnectedClients[hostClientId]);
if ((createPlayerObject == null && NetworkConfig.CreatePlayerPrefab) || (createPlayerObject != null && createPlayerObject.Value))
{
NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(false, 0, (prefabHash == null ? NetworkConfig.PlayerPrefabHash.Value : prefabHash.Value), null, position, rotation);
SpawnManager.SpawnNetworkedObjectLocally(netObject, SpawnManager.GetNetworkObjectId(), false, true, hostClientId, payloadStream, payloadStream != null, payloadStream == null ? 0 : (int)payloadStream.Length, false, false);
if (netObject.CheckObjectVisibility == null || netObject.CheckObjectVisibility(hostClientId))
{
netObject.observers.Add(hostClientId);
}
}
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
if (OnServerStarted != null)
OnServerStarted.Invoke();
return tasks;
}
public void SetSingleton()
{
Singleton = this;
if (OnSingletonReady != null)
OnSingletonReady();
}
private void Awake()
{
rpcQueueContainer = new RpcQueueContainer(false);
//Note: Since frame history is not being used, this is set to 0
//To test frame history, increase the number to (n) where n > 0
rpcQueueContainer.Initialize(0);
}
private void OnEnable()
{
if (Singleton != null && Singleton != this)
{
Destroy(gameObject);
return;
}
// Register INetworkUpdateSystem
this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
SetSingleton();
if (DontDestroy)
DontDestroyOnLoad(gameObject);
if (RunInBackground)
Application.runInBackground = true;
}
private void OnDisable()
{
// Unregister INetworkUpdateSystem
this.UnregisterAllNetworkUpdates();
}
private void OnDestroy()
{
//NSS: This is ok to leave this check here
rpcQueueContainer?.Shutdown();
if (Singleton != null && Singleton == this)
{
Singleton = null;
Shutdown();
}
}
public void Shutdown()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Shutdown()");
NetworkProfiler.Stop();
IsListening = false;
IsServer = false;
IsClient = false;
NetworkConfig.NetworkTransport.OnTransportEvent -= HandleRawTransportPoll;
SpawnManager.DestroyNonSceneObjects();
SpawnManager.ServerResetShudownStateForSceneObjects();
//The Transport is set during Init time, thus it is possible for the Transport to be null
if (NetworkConfig != null && NetworkConfig.NetworkTransport != null)
NetworkConfig.NetworkTransport.Shutdown();
if (rpcQueueContainer != null)
{
rpcQueueContainer.Shutdown();
rpcQueueContainer = null;
}
}
// INetworkUpdateSystem
public void NetworkUpdate(NetworkUpdateStage updateStage)
{
switch (updateStage)
{
case NetworkUpdateStage.EarlyUpdate:
OnNetworkEarlyUpdate();
break;
case NetworkUpdateStage.PreUpdate:
OnNetworkPreUpdate();
break;
}
}
private float m_LastReceiveTickTime;
private float m_LastEventTickTime;
private float m_EventOvershootCounter;
private float m_LastTimeSyncTime;
private void OnNetworkEarlyUpdate()
{
if (IsListening)
{
// Process received data
if ((NetworkTime - m_LastReceiveTickTime >= (1f / NetworkConfig.ReceiveTickrate)) || NetworkConfig.ReceiveTickrate <= 0)
{
ProfilerStatManager.rcvTickRate.Record();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_ReceiveTick.Begin();
#endif
var IsLoopBack = false;
NetworkProfiler.StartTick(TickType.Receive);
//If we are in loopback mode, we don't need to touch the transport
if (!IsLoopBack)
{
NetEventType eventType;
int processedEvents = 0;
do
{
processedEvents++;
eventType = NetworkConfig.NetworkTransport.PollEvent(out ulong clientId, out Channel channel, out ArraySegment<byte> payload, out float receiveTime);
HandleRawTransportPoll(eventType, clientId, channel, payload, receiveTime);
// 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 (IsListening && (eventType != NetEventType.Nothing) && (NetworkConfig.MaxReceiveEventsPerTickRate <= 0 || processedEvents < NetworkConfig.MaxReceiveEventsPerTickRate));
}
m_LastReceiveTickTime = NetworkTime;
NetworkProfiler.EndTick();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_ReceiveTick.End();
#endif
}
}
}
private void OnNetworkPreUpdate()
{
if (IsListening)
{
if (((NetworkTime - m_LastEventTickTime >= (1f / NetworkConfig.EventTickrate))))
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_EventTick.Begin();
#endif
#if UNITY_EDITOR
NetworkProfiler.StartTick(TickType.Event);
#endif
if (IsServer)
{
m_EventOvershootCounter += ((NetworkTime - m_LastEventTickTime) - (1f / NetworkConfig.EventTickrate));
LagCompensationManager.AddFrames();
}
if (NetworkConfig.EnableNetworkedVar)
{
// Do NetworkedVar updates
NetworkedBehaviour.NetworkedBehaviourUpdate();
}
if (!IsServer && NetworkConfig.EnableMessageBuffering)
{
BufferManager.CleanBuffer();
}
if (IsServer)
{
m_LastEventTickTime = NetworkTime;
}
#if UNITY_EDITOR
NetworkProfiler.EndTick();
#endif
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_EventTick.End();
#endif
}
else if (IsServer && m_EventOvershootCounter >= ((1f / NetworkConfig.EventTickrate)))
{
#if UNITY_EDITOR
NetworkProfiler.StartTick(TickType.Event);
#endif
//We run this one to compensate for previous update overshoots.
m_EventOvershootCounter -= (1f / NetworkConfig.EventTickrate);
LagCompensationManager.AddFrames();
#if UNITY_EDITOR
NetworkProfiler.EndTick();
#endif
}
if (IsServer && NetworkConfig.EnableTimeResync && NetworkTime - m_LastTimeSyncTime >= NetworkConfig.TimeResyncInterval)
{
#if UNITY_EDITOR
NetworkProfiler.StartTick(TickType.Event);
#endif
SyncTime();
m_LastTimeSyncTime = NetworkTime;
#if UNITY_EDITOR
NetworkProfiler.EndTick();
#endif
}
if (!Mathf.Approximately(networkTimeOffset, currentNetworkTimeOffset)) {
// Smear network time adjustments by no more than 200ms per second. This should help code deal with
// changes more gracefully, since the network time will always flow forward at a reasonable pace.
float maxDelta = Mathf.Max(0.001f, 0.2f * Time.unscaledDeltaTime);
currentNetworkTimeOffset += Mathf.Clamp(networkTimeOffset - currentNetworkTimeOffset, -maxDelta, maxDelta);
}
}
}
internal void UpdateNetworkTime(ulong clientId, float netTime, float receiveTime, bool warp = false)
{
float rtt = NetworkConfig.NetworkTransport.GetCurrentRtt(clientId) / 1000f;
networkTimeOffset = netTime - receiveTime + rtt / 2f;
if (warp) {
currentNetworkTimeOffset = networkTimeOffset;
}
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo($"Received network time {netTime}, RTT to server is {rtt}, {(warp ? "setting" : "smearing")} offset to {networkTimeOffset} (delta {networkTimeOffset - currentNetworkTimeOffset})");
}
internal void SendConnectionRequest()
{
using (PooledBitStream stream = PooledBitStream.Get())
{
using (PooledBitWriter writer = PooledBitWriter.Get(stream))
{
writer.WriteUInt64Packed(NetworkConfig.GetConfig());
if (NetworkConfig.ConnectionApproval)
writer.WriteByteArray(NetworkConfig.ConnectionData);
}
InternalMessageSender.Send(ServerClientId, MLAPIConstants.MLAPI_CONNECTION_REQUEST, Channel.Internal, stream, SecuritySendFlags.Authenticated | SecuritySendFlags.Encrypted);
}
}
private IEnumerator ApprovalTimeout(ulong clientId)
{
float timeStarted = NetworkTime;
//We yield every frame incase a pending client disconnects and someone else gets its connection id
while (NetworkTime - timeStarted < NetworkConfig.ClientConnectionBufferTimeout && PendingClients.ContainsKey(clientId))
{
yield return null;
}
if (PendingClients.ContainsKey(clientId) && !ConnectedClients.ContainsKey(clientId))
{
// Timeout
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Client " + clientId + " Handshake Timed Out");
DisconnectClient(clientId);
}
}
internal IEnumerator TimeOutSwitchSceneProgress(SceneSwitchProgress switchSceneProgress)
{
yield return new WaitForSecondsRealtime(NetworkConfig.LoadSceneTimeOut);
switchSceneProgress.SetTimedOut();
}
private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, Channel channel, ArraySegment<byte> payload, float receiveTime)
{
ProfilerStatManager.bytesRcvd.Record(payload.Count);
switch (eventType)
{
case NetEventType.Connect:
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportConnect.Begin();
#endif
NetworkProfiler.StartEvent(TickType.Receive, (uint)payload.Count, channel, "TRANSPORT_CONNECT");
if (IsServer)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Client Connected");
#if !DISABLE_CRYPTOGRAPHY
if (NetworkConfig.EnableEncryption)
{
// This client is required to complete the crypto-hail exchange.
using (PooledBitStream hailStream = PooledBitStream.Get())
{
using (PooledBitWriter hailWriter = PooledBitWriter.Get(hailStream))
{
if (NetworkConfig.SignKeyExchange)
{
// Write certificate
hailWriter.WriteByteArray(NetworkConfig.ServerX509CertificateBytes);
}
// Write key exchange public part
EllipticDiffieHellman diffieHellman = new EllipticDiffieHellman(EllipticDiffieHellman.DEFAULT_CURVE, EllipticDiffieHellman.DEFAULT_GENERATOR, EllipticDiffieHellman.DEFAULT_ORDER);
byte[] diffieHellmanPublicPart = diffieHellman.GetPublicKey();
hailWriter.WriteByteArray(diffieHellmanPublicPart);
PendingClients.Add(clientId, new PendingClient()
{
ClientId = clientId,
ConnectionState = PendingClient.State.PendingHail,
KeyExchange = diffieHellman
});
if (NetworkConfig.SignKeyExchange)
{
// Write public part signature (signed by certificate private)
X509Certificate2 certificate = NetworkConfig.ServerX509Certificate;
if (!certificate.HasPrivateKey)
throw new CryptographicException("[MLAPI] No private key was found in server certificate. Unable to sign key exchange");
RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider;
DSACryptoServiceProvider dsa = certificate.PrivateKey as DSACryptoServiceProvider;
if (rsa != null)
{
// RSA is 0
hailWriter.WriteByte(0);
using (SHA256Managed sha = new SHA256Managed())
{
hailWriter.WriteByteArray(rsa.SignData(diffieHellmanPublicPart, sha));
}
}
else if (dsa != null)
{
// DSA is 1
hailWriter.WriteByte(1);
using (SHA256Managed sha = new SHA256Managed())
{
hailWriter.WriteByteArray(dsa.SignData(sha.ComputeHash(diffieHellmanPublicPart)));
}
}
else
{
throw new CryptographicException("[MLAPI] Only RSA and DSA certificates are supported. No valid RSA or DSA key was found");
}
}
}
// Send the hail
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CERTIFICATE_HAIL, Transport.MLAPI_INTERNAL_CHANNEL, hailStream, SecuritySendFlags.None);
}
}
else
{
#endif
PendingClients.Add(clientId, new PendingClient()
{
ClientId = clientId,
ConnectionState = PendingClient.State.PendingConnection
});
#if !DISABLE_CRYPTOGRAPHY
}
#endif
StartCoroutine(ApprovalTimeout(clientId));
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Connected");
if (!NetworkConfig.EnableEncryption)
SendConnectionRequest();
StartCoroutine(ApprovalTimeout(clientId));
}
NetworkProfiler.EndEvent();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportConnect.End();
#endif
break;
case NetEventType.Data: