-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathUnityTransport.cs
More file actions
1804 lines (1568 loc) · 76 KB
/
UnityTransport.cs
File metadata and controls
1804 lines (1568 loc) · 76 KB
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
// NetSim Implementation compilation boilerplate
// All references to UNITY_MP_TOOLS_NETSIM_IMPLEMENTATION_ENABLED should be defined in the same way,
// as any discrepancies are likely to result in build failures
#if UNITY_EDITOR || (DEVELOPMENT_BUILD && !UNITY_MP_TOOLS_NETSIM_DISABLED_IN_DEVELOP) || (!DEVELOPMENT_BUILD && UNITY_MP_TOOLS_NETSIM_ENABLED_IN_RELEASE)
#define UNITY_MP_TOOLS_NETSIM_IMPLEMENTATION_ENABLED
#endif
using System;
using System.Collections.Generic;
#if HOSTNAME_RESOLUTION_AVAILABLE && UTP_TRANSPORT_2_4_ABOVE
using System.Text.RegularExpressions;
#endif
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Networking.Transport;
using Unity.Networking.Transport.Relay;
using Unity.Networking.Transport.TLS;
using Unity.Networking.Transport.Utilities;
using UnityEngine;
using NetcodeEvent = Unity.Netcode.NetworkEvent;
using TransportError = Unity.Networking.Transport.Error.StatusCode;
using TransportEvent = Unity.Networking.Transport.NetworkEvent.Type;
namespace Unity.Netcode.Transports.UTP
{
/// <summary>
/// Provides an interface that overrides the ability to create your own drivers and pipelines
/// </summary>
public interface INetworkStreamDriverConstructor
{
/// <summary>
/// Creates the internal NetworkDriver
/// </summary>
/// <param name="transport">The owner transport</param>
/// <param name="driver">The driver</param>
/// <param name="unreliableFragmentedPipeline">The UnreliableFragmented NetworkPipeline</param>
/// <param name="unreliableSequencedFragmentedPipeline">The UnreliableSequencedFragmented NetworkPipeline</param>
/// <param name="reliableSequencedPipeline">The ReliableSequenced NetworkPipeline</param>
void CreateDriver(
UnityTransport transport,
out NetworkDriver driver,
out NetworkPipeline unreliableFragmentedPipeline,
out NetworkPipeline unreliableSequencedFragmentedPipeline,
out NetworkPipeline reliableSequencedPipeline);
}
/// <summary>
/// The Netcode for GameObjects NetworkTransport for UnityTransport.
/// Note: This is highly recommended to use over UNet.
/// </summary>
[AddComponentMenu("Netcode/Unity Transport")]
public partial class UnityTransport : NetworkTransport, INetworkStreamDriverConstructor
{
/// <summary>
/// Enum type stating the type of protocol
/// </summary>
public enum ProtocolType
{
/// <summary>
/// Unity Transport Protocol
/// </summary>
UnityTransport,
/// <summary>
/// Unity Transport Protocol over Relay
/// </summary>
RelayUnityTransport,
}
/// <summary>
/// The default maximum (receive) packet queue size
/// </summary>
public const int InitialMaxPacketQueueSize = 128;
/// <summary>
/// The default maximum payload size
/// </summary>
public const int InitialMaxPayloadSize = 6 * 1024;
/// <summary>
/// The default maximum send queue size
/// </summary>
[Obsolete("MaxSendQueueSize is now determined dynamically (can still be set programmatically using the MaxSendQueueSize property). This initial value is not used anymore.", false)]
public const int InitialMaxSendQueueSize = 16 * InitialMaxPayloadSize;
// Maximum reliable throughput, assuming the full reliable window can be sent on every
// frame at 60 FPS. This will be a large over-estimation in any realistic scenario.
private const int k_MaxReliableThroughput = (NetworkParameterConstants.MTU * 64 * 60) / 1000; // bytes per millisecond
private static ConnectionAddressData s_DefaultConnectionAddressData = new ConnectionAddressData { Address = "127.0.0.1", Port = 7777, ServerListenAddress = string.Empty };
#pragma warning disable IDE1006 // Naming Styles
/// <summary>
/// The global <see cref="INetworkStreamDriverConstructor"/> implementation
/// </summary>
public static INetworkStreamDriverConstructor s_DriverConstructor;
#pragma warning restore IDE1006 // Naming Styles
/// <summary>
/// Returns either the global <see cref="INetworkStreamDriverConstructor"/> implementation or the current <see cref="UnityTransport"/> instance
/// </summary>
public INetworkStreamDriverConstructor DriverConstructor => s_DriverConstructor ?? this;
[Tooltip("Which protocol should be selected (Relay/Non-Relay).")]
[SerializeField]
private ProtocolType m_ProtocolType;
[Tooltip("Per default the client/server will communicate over UDP. Set to true to communicate with WebSocket.")]
[SerializeField]
private bool m_UseWebSockets = false;
/// <summary>Whether to use WebSockets as the protocol of communication. Default is UDP.</summary>
public bool UseWebSockets
{
get => m_UseWebSockets;
set => m_UseWebSockets = value;
}
[Tooltip("Per default the client/server communication will not be encrypted. Select true to enable DTLS for UDP and TLS for Websocket.")]
[SerializeField]
private bool m_UseEncryption = false;
/// <summary>
/// Whether to use encryption (default is false). Note that unless using Unity Relay, encryption requires
/// providing certificate information with <see cref="SetClientSecrets"/> and <see cref="SetServerSecrets"/>.
/// </summary>
public bool UseEncryption
{
get => m_UseEncryption;
set => m_UseEncryption = value;
}
[Tooltip("The maximum amount of packets that can be in the internal send/receive queues. Basically this is how many packets can be sent/received in a single update/frame.")]
[SerializeField]
private int m_MaxPacketQueueSize = InitialMaxPacketQueueSize;
/// <summary>The maximum amount of packets that can be in the internal send/receive queues.</summary>
/// <remarks>Basically this is how many packets can be sent/received in a single update/frame.</remarks>
public int MaxPacketQueueSize
{
get => m_MaxPacketQueueSize;
set => m_MaxPacketQueueSize = value;
}
[Tooltip("The maximum size of an unreliable payload that can be handled by the transport.")]
[SerializeField]
private int m_MaxPayloadSize = InitialMaxPayloadSize;
/// <summary>The maximum size of an unreliable payload that can be handled by the transport.</summary>
public int MaxPayloadSize
{
get => m_MaxPayloadSize;
set => m_MaxPayloadSize = value;
}
private int m_MaxSendQueueSize = 0;
/// <summary>The maximum size in bytes of the transport send queue.</summary>
/// <remarks>
/// The send queue accumulates messages for batching and stores messages when other internal
/// send queues are full. Note that there should not be any need to set this value manually
/// since the send queue size is dynamically sized based on need.
///
/// This value should only be set if you have particular requirements (e.g. if you want to
/// limit the memory usage of the send queues). Note however that setting this value too low
/// can easily lead to disconnections under heavy traffic.
/// </remarks>
public int MaxSendQueueSize
{
get => m_MaxSendQueueSize;
set => m_MaxSendQueueSize = value;
}
[Tooltip("Timeout in milliseconds after which a heartbeat is sent if there is no activity.")]
[SerializeField]
private int m_HeartbeatTimeoutMS = NetworkParameterConstants.HeartbeatTimeoutMS;
/// <summary>Timeout in milliseconds after which a heartbeat is sent if there is no activity.</summary>
public int HeartbeatTimeoutMS
{
get => m_HeartbeatTimeoutMS;
set => m_HeartbeatTimeoutMS = value;
}
[Tooltip("Timeout in milliseconds indicating how long we will wait until we send a new connection attempt.")]
[SerializeField]
private int m_ConnectTimeoutMS = NetworkParameterConstants.ConnectTimeoutMS;
/// <summary>
/// Timeout in milliseconds indicating how long we will wait until we send a new connection attempt.
/// </summary>
public int ConnectTimeoutMS
{
get => m_ConnectTimeoutMS;
set => m_ConnectTimeoutMS = value;
}
[Tooltip("The maximum amount of connection attempts we will try before disconnecting.")]
[SerializeField]
private int m_MaxConnectAttempts = NetworkParameterConstants.MaxConnectAttempts;
/// <summary>The maximum amount of connection attempts we will try before disconnecting.</summary>
public int MaxConnectAttempts
{
get => m_MaxConnectAttempts;
set => m_MaxConnectAttempts = value;
}
[Tooltip("Inactivity timeout after which a connection will be disconnected. The connection needs to receive data from the connected endpoint within this timeout. Note that with heartbeats enabled, simply not sending any data will not be enough to trigger this timeout (since heartbeats count as connection events).")]
[SerializeField]
private int m_DisconnectTimeoutMS = NetworkParameterConstants.DisconnectTimeoutMS;
/// <summary>Inactivity timeout after which a connection will be disconnected.</summary>
/// <remarks>
/// The connection needs to receive data from the connected endpoint within this timeout.
/// Note that with heartbeats enabled, simply not sending any data will not be enough to
/// trigger this timeout (since heartbeats count as connection events).
/// </remarks>
public int DisconnectTimeoutMS
{
get => m_DisconnectTimeoutMS;
set => m_DisconnectTimeoutMS = value;
}
/// <summary>
/// Structure to store the address to connect to
/// </summary>
[Serializable]
public struct ConnectionAddressData
{
/// <summary>
/// IP address of the server (address to which clients will connect to).
/// </summary>
[Tooltip("IP address of the server (address to which clients will connect to).")]
[SerializeField]
public string Address;
/// <summary>
/// UDP port of the server.
/// </summary>
[Tooltip("UDP port of the server.")]
[SerializeField]
public ushort Port;
/// <summary>
/// IP address the server will listen on. If not provided, will use localhost.
/// </summary>
[Tooltip("IP address the server will listen on. If not provided, will use localhost.")]
[SerializeField]
public string ServerListenAddress;
private static NetworkEndpoint ParseNetworkEndpoint(string ip, ushort port, bool silent = false)
{
NetworkEndpoint endpoint = default;
if (!NetworkEndpoint.TryParse(ip, port, out endpoint, NetworkFamily.Ipv4) &&
!NetworkEndpoint.TryParse(ip, port, out endpoint, NetworkFamily.Ipv6))
{
#if HOSTNAME_RESOLUTION_AVAILABLE && UTP_TRANSPORT_2_4_ABOVE
return default;
#else // If the user does not have the most recent version of UnityTransport installed
if (!silent)
{
Debug.LogError($"Invalid network endpoint: {ip}:{port}.");
}
#endif
}
return endpoint;
}
/// <summary>
/// Endpoint (IP address and port) clients will connect to.
/// </summary>
public NetworkEndpoint ServerEndPoint => ParseNetworkEndpoint(Address, Port);
/// <summary>
/// Endpoint (IP address and port) server will listen/bind on.
/// </summary>
public NetworkEndpoint ListenEndPoint
{
get
{
if (string.IsNullOrEmpty(ServerListenAddress))
{
var ep = NetworkEndpoint.LoopbackIpv4;
// If an address was entered and it's IPv6, switch to using ::1 as the
// default listen address. (Otherwise we always assume IPv4.)
if (!string.IsNullOrEmpty(Address) && ServerEndPoint.Family == NetworkFamily.Ipv6)
{
ep = NetworkEndpoint.LoopbackIpv6;
}
return ep.WithPort(Port);
}
else
{
return ParseNetworkEndpoint(ServerListenAddress, Port);
}
}
}
/// <summary>
/// Returns true if the end point address is of type <see cref="NetworkFamily.Ipv6"/>.
/// </summary>
public bool IsIpv6 => !string.IsNullOrEmpty(Address) && ParseNetworkEndpoint(Address, Port, true).Family == NetworkFamily.Ipv6;
}
/// <summary>
/// The connection (address) data for this <see cref="UnityTransport"/> instance.
/// This is where you can change IP Address, Port, or server's listen address.
/// <see cref="ConnectionAddressData"/>
/// </summary>
public ConnectionAddressData ConnectionData = s_DefaultConnectionAddressData;
/// <summary>
/// Parameters for the Network Simulator
/// </summary>
[Serializable]
public struct SimulatorParameters
{
/// <summary>
/// Delay to add to every send and received packet (in milliseconds). Only applies in the editor and in development builds. The value is ignored in production builds.
/// </summary>
[Tooltip("Delay to add to every send and received packet (in milliseconds). Only applies in the editor and in development builds. The value is ignored in production builds.")]
[SerializeField]
public int PacketDelayMS;
/// <summary>
/// Jitter (random variation) to add/substract to the packet delay (in milliseconds). Only applies in the editor and in development builds. The value is ignored in production builds.
/// </summary>
[Tooltip("Jitter (random variation) to add/substract to the packet delay (in milliseconds). Only applies in the editor and in development builds. The value is ignored in production builds.")]
[SerializeField]
public int PacketJitterMS;
/// <summary>
/// Percentage of sent and received packets to drop. Only applies in the editor and in the editor and in developments builds.
/// </summary>
[Tooltip("Percentage of sent and received packets to drop. Only applies in the editor and in the editor and in developments builds.")]
[SerializeField]
public int PacketDropRate;
}
/// <summary>
/// Can be used to simulate poor network conditions such as:
/// - packet delay/latency
/// - packet jitter (variances in latency, see: https://en.wikipedia.org/wiki/Jitter)
/// - packet drop rate (packet loss)
/// </summary>
[Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)]
[HideInInspector]
public SimulatorParameters DebugSimulator = new SimulatorParameters
{
PacketDelayMS = 0,
PacketJitterMS = 0,
PacketDropRate = 0
};
internal uint? DebugSimulatorRandomSeed { get; set; } = null;
private struct PacketLossCache
{
public int PacketsReceived;
public int PacketsDropped;
public float PacketLoss;
};
internal static event Action<int, NetworkDriver> TransportInitialized;
internal static event Action<int> TransportDisposed;
/// <summary>
/// Provides access to the <see cref="NetworkDriver"/> for this instance.
/// </summary>
protected NetworkDriver m_Driver;
/// <summary>
/// Gets a reference to the <see cref="NetworkDriver"/>.
/// </summary>
/// <returns>ref <see cref="NetworkDriver"/></returns>
public ref NetworkDriver GetNetworkDriver()
{
return ref m_Driver;
}
/// <summary>
/// Gets the local sytem's <see cref="NetworkEndpoint"/> that is assigned for the current network session.
/// </summary>
/// <remarks>
/// If the driver is not created it will return an invalid <see cref="NetworkEndpoint"/>.
/// </remarks>
/// <returns><see cref="NetworkEndpoint"/></returns>
public NetworkEndpoint GetLocalEndpoint()
{
if (m_Driver.IsCreated)
{
return m_Driver.GetLocalEndpoint();
}
return new NetworkEndpoint();
}
private PacketLossCache m_PacketLossCache = new PacketLossCache();
private NetworkSettings m_NetworkSettings;
private ulong m_ServerClientId;
private NetworkPipeline m_UnreliableFragmentedPipeline;
private NetworkPipeline m_UnreliableSequencedFragmentedPipeline;
private NetworkPipeline m_ReliableSequencedPipeline;
/// <summary>
/// The client id used to represent the server.
/// </summary>
public override ulong ServerClientId => m_ServerClientId;
/// <summary>
/// The current ProtocolType used by the transport
/// </summary>
public ProtocolType Protocol => m_ProtocolType;
private RelayServerData m_RelayServerData;
/// <summary>
/// NetworkManager associated to this transport instance
/// </summary>
protected NetworkManager m_NetworkManager;
private IRealTimeProvider m_RealTimeProvider;
/// <summary>
/// SendQueue dictionary is used to batch events instead of sending them immediately.
/// </summary>
private readonly Dictionary<SendTarget, BatchedSendQueue> m_SendQueue = new Dictionary<SendTarget, BatchedSendQueue>();
// Since reliable messages may be spread out over multiple transport payloads, it's possible
// to receive only parts of a message in an update. We thus keep the reliable receive queues
// around to avoid losing partial messages.
private readonly Dictionary<ulong, BatchedReceiveQueue> m_ReliableReceiveQueues = new Dictionary<ulong, BatchedReceiveQueue>();
private void InitDriver()
{
DriverConstructor.CreateDriver(
this,
out m_Driver,
out m_UnreliableFragmentedPipeline,
out m_UnreliableSequencedFragmentedPipeline,
out m_ReliableSequencedPipeline);
TransportInitialized?.Invoke(GetInstanceID(), m_Driver);
}
private void DisposeInternals()
{
if (m_Driver.IsCreated)
{
m_Driver.Dispose();
}
m_NetworkSettings.Dispose();
foreach (var queue in m_SendQueue.Values)
{
queue.Dispose();
}
m_SendQueue.Clear();
TransportDisposed?.Invoke(GetInstanceID());
}
private NetworkPipeline SelectSendPipeline(NetworkDelivery delivery)
{
switch (delivery)
{
case NetworkDelivery.Unreliable:
return m_UnreliableFragmentedPipeline;
case NetworkDelivery.UnreliableSequenced:
return m_UnreliableSequencedFragmentedPipeline;
case NetworkDelivery.Reliable:
case NetworkDelivery.ReliableSequenced:
case NetworkDelivery.ReliableFragmentedSequenced:
return m_ReliableSequencedPipeline;
default:
Debug.LogError($"Unknown {nameof(NetworkDelivery)} value: {delivery}");
return NetworkPipeline.Null;
}
}
#if HOSTNAME_RESOLUTION_AVAILABLE && UTP_TRANSPORT_2_4_ABOVE
private bool IsValidFqdn(string fqdn)
{
// Regular expression to validate FQDN
string pattern = @"^(?=.{1,255}$)(?!-)[A-Za-z0-9-]{1,63}(?<!-)\.(?!-)(?:[A-Za-z0-9-]{1,63}\.?)+[A-Za-z]{2,6}$";
var regex = new Regex(pattern);
return regex.IsMatch(fqdn);
}
#endif
private bool ClientBindAndConnect()
{
var serverEndpoint = default(NetworkEndpoint);
if (m_ProtocolType == ProtocolType.RelayUnityTransport)
{
//This comparison is currently slow since RelayServerData does not implement a custom comparison operator that doesn't use
//reflection, but this does not live in the context of a performance-critical loop, it runs once at initial connection time.
if (m_RelayServerData.Equals(default(RelayServerData)))
{
Debug.LogError("You must call SetRelayServerData() at least once before calling StartClient.");
return false;
}
m_NetworkSettings.WithRelayParameters(ref m_RelayServerData, m_HeartbeatTimeoutMS);
serverEndpoint = m_RelayServerData.Endpoint;
}
else
{
serverEndpoint = ConnectionData.ServerEndPoint;
}
// Verify the endpoint is valid before proceeding
if (serverEndpoint.Family == NetworkFamily.Invalid)
{
#if HOSTNAME_RESOLUTION_AVAILABLE && UTP_TRANSPORT_2_4_ABOVE
// If it's not valid, assure it meets FQDN standards
if (IsValidFqdn(ConnectionData.Address))
{
// If so, then proceed with driver initialization and attempt to connect
InitDriver();
m_Driver.Connect(ConnectionData.Address, ConnectionData.Port);
return true;
}
else
{
// If not then log an error and return false
Debug.LogError($"Target server network address ({ConnectionData.Address}) is not a valid Fully Qualified Domain Name!");
return false;
}
#else
Debug.LogError($"Target server network address ({ConnectionData.Address}) is {nameof(NetworkFamily.Invalid)}!");
return false;
#endif
}
InitDriver();
var bindEndpoint = serverEndpoint.Family == NetworkFamily.Ipv6 ? NetworkEndpoint.AnyIpv6 : NetworkEndpoint.AnyIpv4;
int result = m_Driver.Bind(bindEndpoint);
if (result != 0)
{
Debug.LogError("Client failed to bind");
return false;
}
Connect(serverEndpoint);
return true;
}
/// <summary>
/// Virtual method that is invoked during <see cref="StartClient"/>.
/// </summary>
/// <param name="serverEndpoint">The <see cref="NetworkEndpoint"/> that the client is connecting to.</param>
/// <returns>A <see cref="NetworkConnection"/> representing the connection to the server, or an invalid connection if the connection attempt fails.</returns>
protected virtual NetworkConnection Connect(NetworkEndpoint serverEndpoint)
{
return m_Driver.Connect(serverEndpoint);
}
private bool ServerBindAndListen(NetworkEndpoint endPoint)
{
// Verify the endpoint is valid before proceeding
if (endPoint.Family == NetworkFamily.Invalid)
{
#if HOSTNAME_RESOLUTION_AVAILABLE && UTP_TRANSPORT_2_4_ABOVE
// If it's not valid, assure it meets FQDN standards
if (!IsValidFqdn(ConnectionData.Address))
{
// If not then log an error and return false
Debug.LogError($"Listen network address ({ConnectionData.Address}) is not a valid {NetworkFamily.Ipv4} or {NetworkFamily.Ipv6} address!");
}
else
{
Debug.LogError($"While ({ConnectionData.Address}) is a valid Fully Qualified Domain Name, you must use a valid {NetworkFamily.Ipv4} or {NetworkFamily.Ipv6} address when binding and listening for connections!");
}
return false;
#else
Debug.LogError($"Network listen address ({ConnectionData.Address}) is {nameof(NetworkFamily.Invalid)}!");
return false;
#endif
}
InitDriver();
int result = m_Driver.Bind(endPoint);
if (result != 0)
{
Debug.LogError("Server failed to bind. This is usually caused by another process being bound to the same port.");
return false;
}
result = m_Driver.Listen();
if (result != 0)
{
Debug.LogError("Server failed to listen.");
return false;
}
return true;
}
private void SetProtocol(ProtocolType inProtocol)
{
m_ProtocolType = inProtocol;
}
/// <summary>Set the relay server data for the server.</summary>
/// <param name="ipv4Address">IP address or hostname of the relay server.</param>
/// <param name="port">UDP port of the relay server.</param>
/// <param name="allocationIdBytes">Allocation ID as a byte array.</param>
/// <param name="keyBytes">Allocation key as a byte array.</param>
/// <param name="connectionDataBytes">Connection data as a byte array.</param>
/// <param name="hostConnectionDataBytes">The HostConnectionData as a byte array.</param>
/// <param name="isSecure">Whether the connection is secure (uses DTLS).</param>
public void SetRelayServerData(string ipv4Address, ushort port, byte[] allocationIdBytes, byte[] keyBytes, byte[] connectionDataBytes, byte[] hostConnectionDataBytes = null, bool isSecure = false)
{
var hostConnectionData = hostConnectionDataBytes ?? connectionDataBytes;
m_RelayServerData = new RelayServerData(ipv4Address, port, allocationIdBytes, connectionDataBytes, hostConnectionData, keyBytes, isSecure);
SetProtocol(ProtocolType.RelayUnityTransport);
}
/// <summary>Set the relay server data (using the lower-level Unity Transport data structure).</summary>
/// <param name="serverData">Data for the Relay server to use.</param>
public void SetRelayServerData(RelayServerData serverData)
{
m_RelayServerData = serverData;
SetProtocol(ProtocolType.RelayUnityTransport);
}
/// <summary>Set the relay server data for the host.</summary>
/// <param name="ipAddress">IP address or hostname of the relay server.</param>
/// <param name="port">UDP port of the relay server.</param>
/// <param name="allocationId">Allocation ID as a byte array.</param>
/// <param name="key">Allocation key as a byte array.</param>
/// <param name="connectionData">Connection data as a byte array.</param>
/// <param name="isSecure">Whether the connection is secure (uses DTLS).</param>
public void SetHostRelayData(string ipAddress, ushort port, byte[] allocationId, byte[] key, byte[] connectionData, bool isSecure = false)
{
SetRelayServerData(ipAddress, port, allocationId, key, connectionData, null, isSecure);
}
/// <summary>Set the relay server data for the host.</summary>
/// <param name="ipAddress">IP address or hostname of the relay server.</param>
/// <param name="port">UDP port of the relay server.</param>
/// <param name="allocationId">Allocation ID as a byte array.</param>
/// <param name="key">Allocation key as a byte array.</param>
/// <param name="connectionData">Connection data as a byte array.</param>
/// <param name="hostConnectionData">Host's connection data as a byte array.</param>
/// <param name="isSecure">Whether the connection is secure (uses DTLS).</param>
public void SetClientRelayData(string ipAddress, ushort port, byte[] allocationId, byte[] key, byte[] connectionData, byte[] hostConnectionData, bool isSecure = false)
{
SetRelayServerData(ipAddress, port, allocationId, key, connectionData, hostConnectionData, isSecure);
}
/// <summary>
/// Sets IP and Port information. This will be ignored if using the Unity Relay and you should call <see cref="SetRelayServerData"/>
/// </summary>
/// <param name="ipv4Address">The remote IP address (despite the name, can be an IPv6 address or a domain name)</param>
/// <param name="port">The remote port</param>
/// <param name="listenAddress">The local listen address</param>
public void SetConnectionData(string ipv4Address, ushort port, string listenAddress = null)
{
ConnectionData = new ConnectionAddressData
{
Address = ipv4Address,
Port = port,
ServerListenAddress = listenAddress ?? ipv4Address
};
SetProtocol(ProtocolType.UnityTransport);
}
/// <summary>
/// Sets IP and Port information. This will be ignored if using the Unity Relay and you should call <see cref="SetRelayServerData"/>
/// </summary>
/// <param name="endPoint">The remote end point</param>
/// <param name="listenEndPoint">The local listen endpoint</param>
public void SetConnectionData(NetworkEndpoint endPoint, NetworkEndpoint listenEndPoint = default)
{
string serverAddress = endPoint.Address.Split(':')[0];
string listenAddress = string.Empty;
if (listenEndPoint != default)
{
listenAddress = listenEndPoint.Address.Split(':')[0];
if (endPoint.Port != listenEndPoint.Port)
{
Debug.LogError($"Port mismatch between server and listen endpoints ({endPoint.Port} vs {listenEndPoint.Port}).");
}
}
SetConnectionData(serverAddress, endPoint.Port, listenAddress);
}
/// <summary>Set the parameters for the debug simulator.</summary>
/// <param name="packetDelay">Packet delay in milliseconds.</param>
/// <param name="packetJitter">Packet jitter in milliseconds.</param>
/// <param name="dropRate">Packet drop percentage.</param>
[Obsolete("SetDebugSimulatorParameters is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)]
public void SetDebugSimulatorParameters(int packetDelay, int packetJitter, int dropRate)
{
if (m_Driver.IsCreated)
{
Debug.LogError("SetDebugSimulatorParameters() must be called before StartClient() or StartServer().");
return;
}
DebugSimulator = new SimulatorParameters
{
PacketDelayMS = packetDelay,
PacketJitterMS = packetJitter,
PacketDropRate = dropRate
};
}
private bool StartRelayServer()
{
//This comparison is currently slow since RelayServerData does not implement a custom comparison operator that doesn't use
//reflection, but this does not live in the context of a performance-critical loop, it runs once at initial connection time.
if (m_RelayServerData.Equals(default(RelayServerData)))
{
Debug.LogError("You must call SetRelayServerData() at least once before calling StartServer.");
return false;
}
else
{
m_NetworkSettings.WithRelayParameters(ref m_RelayServerData, m_HeartbeatTimeoutMS);
return ServerBindAndListen(NetworkEndpoint.AnyIpv4);
}
}
[BurstCompile]
private struct SendBatchedMessagesJob : IJob
{
public NetworkDriver.Concurrent Driver;
public SendTarget Target;
public BatchedSendQueue Queue;
public NetworkPipeline ReliablePipeline;
public int MTU;
public void Execute()
{
var clientId = Target.ClientId;
var connection = ParseClientId(clientId);
var pipeline = Target.NetworkPipeline;
while (!Queue.IsEmpty)
{
var result = Driver.BeginSend(pipeline, connection, out var writer);
if (result != (int)TransportError.Success)
{
Debug.LogError($"Send error on connection {clientId}: {ErrorUtilities.ErrorToFixedString(result)}");
return;
}
// We don't attempt to send entire payloads over the reliable pipeline. Instead we
// fragment it manually. This is safe and easy to do since the reliable pipeline
// basically implements a stream, so as long as we separate the different messages
// in the stream (the send queue does that automatically) we are sure they'll be
// reassembled properly at the other end. This allows us to lift the limit of ~44KB
// on reliable payloads (because of the reliable window size).
var written = pipeline == ReliablePipeline ? Queue.FillWriterWithBytes(ref writer, MTU) : Queue.FillWriterWithMessages(ref writer, MTU);
result = Driver.EndSend(writer);
if (result == written)
{
// Batched message was sent successfully. Remove it from the queue.
Queue.Consume(written);
}
else
{
// Some error occured. If it's just the UTP queue being full, then don't log
// anything since that's okay (the unsent message(s) are still in the queue
// and we'll retry sending them later). Otherwise log the error and remove the
// message from the queue (we don't want to resend it again since we'll likely
// just get the same error again).
if (result != (int)TransportError.NetworkSendQueueFull)
{
Debug.LogError($"Send error on connection {clientId}: {ErrorUtilities.ErrorToFixedString(result)}");
Queue.Consume(written);
}
return;
}
}
}
}
// Send as many batched messages from the queue as possible.
private void SendBatchedMessages(SendTarget sendTarget, BatchedSendQueue queue)
{
if (!m_Driver.IsCreated)
{
return;
}
var mtu = 0;
if (m_NetworkManager)
{
var ngoClientId = m_NetworkManager.ConnectionManager.TransportIdToClientId(sendTarget.ClientId);
mtu = m_NetworkManager.GetPeerMTU(ngoClientId);
}
new SendBatchedMessagesJob
{
Driver = m_Driver.ToConcurrent(),
Target = sendTarget,
Queue = queue,
ReliablePipeline = m_ReliableSequencedPipeline,
MTU = mtu,
}.Run();
}
private bool AcceptConnection()
{
var connection = m_Driver.Accept();
if (connection == default)
{
return false;
}
InvokeOnTransportEvent(NetcodeEvent.Connect,
ParseClientId(connection),
default,
m_RealTimeProvider.RealTimeSinceStartup);
return true;
}
private void ReceiveMessages(ulong clientId, NetworkPipeline pipeline, DataStreamReader dataReader)
{
BatchedReceiveQueue queue;
if (pipeline == m_ReliableSequencedPipeline)
{
if (m_ReliableReceiveQueues.TryGetValue(clientId, out queue))
{
queue.PushReader(dataReader);
}
else
{
queue = new BatchedReceiveQueue(dataReader);
m_ReliableReceiveQueues[clientId] = queue;
}
}
else
{
queue = new BatchedReceiveQueue(dataReader);
}
while (!queue.IsEmpty)
{
var message = queue.PopMessage();
if (message == default)
{
// Only happens if there's only a partial message in the queue (rare).
break;
}
InvokeOnTransportEvent(NetcodeEvent.Data, clientId, message, m_RealTimeProvider.RealTimeSinceStartup);
}
}
private bool ProcessEvent()
{
var eventType = m_Driver.PopEvent(out var networkConnection, out var reader, out var pipeline);
var clientId = ParseClientId(networkConnection);
switch (eventType)
{
case TransportEvent.Connect:
{
InvokeOnTransportEvent(NetcodeEvent.Connect,
clientId,
default,
m_RealTimeProvider.RealTimeSinceStartup);
m_ServerClientId = clientId;
return true;
}
case TransportEvent.Disconnect:
{
// If we're a client and had not yet set the server client ID, it means
// our connection to the server failed to be established. Any other case
// means a clean disconnect that doesn't require logging.
if (!m_Driver.Listening && m_ServerClientId == default)
{
Debug.LogError("Failed to connect to server.");
}
m_ServerClientId = default;
m_ReliableReceiveQueues.Remove(clientId);
ClearSendQueuesForClientId(clientId);
InvokeOnTransportEvent(NetcodeEvent.Disconnect,
clientId,
default,
m_RealTimeProvider.RealTimeSinceStartup);
return true;
}
case TransportEvent.Data:
{
ReceiveMessages(clientId, pipeline, reader);
return true;
}
}
return false;
}
/// <summary>
/// Handles accepting new connections and processing transport events.
/// </summary>
protected override void OnEarlyUpdate()
{
if (m_Driver.IsCreated)
{
if (m_ProtocolType == ProtocolType.RelayUnityTransport && m_Driver.GetRelayConnectionStatus() == RelayConnectionStatus.AllocationInvalid)
{
Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " +
"Use NetworkManager.OnTransportFailure to be notified of such events programmatically.");
InvokeOnTransportEvent(NetcodeEvent.TransportFailure, 0, default, m_RealTimeProvider.RealTimeSinceStartup);
return;
}
m_Driver.ScheduleUpdate().Complete();
// Process any new connections
while (AcceptConnection() && m_Driver.IsCreated)
{
;
}
// Process any transport events (i.e. connect, disconnect, data, etc)
while (ProcessEvent() && m_Driver.IsCreated)
{
;
}
}
base.OnEarlyUpdate();
}
/// <summary>
/// Handles sending any queued batched messages.
/// </summary>
protected override void OnPostLateUpdate()
{
if (m_Driver.IsCreated)
{
foreach (var kvp in m_SendQueue)
{
SendBatchedMessages(kvp.Key, kvp.Value);
}
// Schedule a flush send as the last transport action for the
// current frame.
m_Driver.ScheduleFlushSend(default).Complete();
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7
if (m_NetworkManager)
{
ExtractNetworkMetrics();
}
#endif
}
base.OnPostLateUpdate();
}
private void OnDestroy()
{
DisposeInternals();
}
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7
private void ExtractNetworkMetrics()
{
if (m_NetworkManager.IsServer)
{
var ngoConnectionIds = m_NetworkManager.ConnectedClients.Keys;