@@ -19,6 +19,49 @@ public interface INetworkStreamDriverConstructor
19
19
void CreateDriver ( UnityTransport transport , out NetworkDriver driver , out NetworkPipeline unreliableSequencedPipeline , out NetworkPipeline reliableSequencedPipeline , out NetworkPipeline reliableSequencedFragmentedPipeline ) ;
20
20
}
21
21
22
+ public static class ErrorUtilities
23
+ {
24
+ private const string k_NetworkSuccess = "Success" ;
25
+ private const string k_NetworkIdMismatch = "NetworkId is invalid, likely caused by stale connection {0}." ;
26
+ private const string k_NetworkVersionMismatch = "NetworkVersion is invalid, likely caused by stale connection {0}." ;
27
+ private const string k_NetworkStateMismatch = "Sending data while connecting on connectionId{0} is now allowed" ;
28
+ private const string k_NetworkPacketOverflow = "Unable to allocate packet due to buffer overflow." ;
29
+ private const string k_NetworkSendQueueFull = "Currently unable to queue packet as there is too many inflight packets." ;
30
+ private const string k_NetworkHeaderInvalid = "Invalid Unity Transport Protocol header." ;
31
+ private const string k_NetworkDriverParallelForErr = "The parallel network driver needs to process a single unique connection per job, processing a single connection multiple times in a parallel for is not supported." ;
32
+ private const string k_NetworkSendHandleInvalid = "Invalid NetworkInterface Send Handle. Likely caused by pipeline send data corruption." ;
33
+ private const string k_NetworkArgumentMismatch = "Invalid NetworkEndpoint Arguments." ;
34
+
35
+ public static string ErrorToString ( Networking . Transport . Error . StatusCode error , ulong connectionId )
36
+ {
37
+ switch ( error )
38
+ {
39
+ case Networking . Transport . Error . StatusCode . Success :
40
+ return k_NetworkSuccess ;
41
+ case Networking . Transport . Error . StatusCode . NetworkIdMismatch :
42
+ return string . Format ( k_NetworkIdMismatch , connectionId ) ;
43
+ case Networking . Transport . Error . StatusCode . NetworkVersionMismatch :
44
+ return string . Format ( k_NetworkVersionMismatch , connectionId ) ;
45
+ case Networking . Transport . Error . StatusCode . NetworkStateMismatch :
46
+ return string . Format ( k_NetworkStateMismatch , connectionId ) ;
47
+ case Networking . Transport . Error . StatusCode . NetworkPacketOverflow :
48
+ return k_NetworkPacketOverflow ;
49
+ case Networking . Transport . Error . StatusCode . NetworkSendQueueFull :
50
+ return k_NetworkSendQueueFull ;
51
+ case Networking . Transport . Error . StatusCode . NetworkHeaderInvalid :
52
+ return k_NetworkHeaderInvalid ;
53
+ case Networking . Transport . Error . StatusCode . NetworkDriverParallelForErr :
54
+ return k_NetworkDriverParallelForErr ;
55
+ case Networking . Transport . Error . StatusCode . NetworkSendHandleInvalid :
56
+ return k_NetworkSendHandleInvalid ;
57
+ case Networking . Transport . Error . StatusCode . NetworkArgumentMismatch :
58
+ return k_NetworkArgumentMismatch ;
59
+ }
60
+
61
+ return $ "Unknown ErrorCode { Enum . GetName ( typeof ( Networking . Transport . Error . StatusCode ) , error ) } ";
62
+ }
63
+ }
64
+
22
65
public class UnityTransport : NetworkTransport , INetworkStreamDriverConstructor
23
66
{
24
67
public enum ProtocolType
@@ -34,23 +77,43 @@ private enum State
34
77
Connected ,
35
78
}
36
79
37
- public const int MaximumMessageLength = 6 * 1024 ;
80
+ public const int InitialBatchQueueSize = 6 * 1024 ;
81
+ public const int InitialMaxPacketSize = NetworkParameterConstants . MTU ;
82
+
83
+ private static ConnectionAddressData s_DefaultConnectionAddressData = new ConnectionAddressData ( )
84
+ { Address = "127.0.0.1" , Port = 7777 } ;
38
85
39
86
#pragma warning disable IDE1006 // Naming Styles
40
87
public static INetworkStreamDriverConstructor s_DriverConstructor ;
41
88
#pragma warning restore IDE1006 // Naming Styles
42
89
public INetworkStreamDriverConstructor DriverConstructor => s_DriverConstructor != null ? s_DriverConstructor : this ;
43
90
91
+ [ Tooltip ( "Which protocol should be selected Relay/Non-Relay" ) ]
44
92
[ SerializeField ] private ProtocolType m_ProtocolType ;
45
- [ SerializeField ] private int m_MessageBufferSize = MaximumMessageLength ;
46
- [ SerializeField ] private int m_ReciveQueueSize = 128 ;
47
- [ SerializeField ] private int m_SendQueueSize = 128 ;
48
93
49
- [ Tooltip ( "The maximum size of the send queue for batching Netcode events" ) ]
50
- [ SerializeField ] private int m_SendQueueBatchSize = 4096 ;
94
+ [ Tooltip ( "Maximum size in bytes for a given packet" ) ]
95
+ [ SerializeField ] private int m_MaximumPacketSize = InitialMaxPacketSize ;
96
+
97
+ [ Tooltip ( "The maximum amount of packets that can be in the send/recv queues" ) ]
98
+ [ SerializeField ] private int m_MaxPacketQueueSize = 128 ;
99
+
100
+ [ Tooltip ( "The maximum size in bytes of the send queue for batching Netcode events" ) ]
101
+ [ SerializeField ] private int m_SendQueueBatchSize = InitialBatchQueueSize ;
51
102
52
- [ SerializeField ] private string m_ServerAddress = "127.0.0.1" ;
53
- [ SerializeField ] private ushort m_ServerPort = 7777 ;
103
+ [ Serializable ]
104
+ public struct ConnectionAddressData
105
+ {
106
+ [ SerializeField ] public string Address ;
107
+ [ SerializeField ] public int Port ;
108
+
109
+ public static implicit operator NetworkEndPoint ( ConnectionAddressData d ) =>
110
+ NetworkEndPoint . Parse ( d . Address , ( ushort ) d . Port ) ;
111
+
112
+ public static implicit operator ConnectionAddressData ( NetworkEndPoint d ) =>
113
+ new ConnectionAddressData ( ) { Address = d . Address . Split ( ':' ) [ 0 ] , Port = d . Port } ;
114
+ }
115
+
116
+ public ConnectionAddressData ConnectionData = s_DefaultConnectionAddressData ;
54
117
55
118
private State m_State = State . Disconnected ;
56
119
private NetworkDriver m_Driver ;
@@ -171,7 +234,7 @@ private bool ClientBindAndConnect()
171
234
}
172
235
else
173
236
{
174
- serverEndpoint = NetworkEndPoint . Parse ( m_ServerAddress , m_ServerPort ) ;
237
+ serverEndpoint = ConnectionData ;
175
238
}
176
239
177
240
InitDriver ( ) ;
@@ -273,8 +336,16 @@ public void SetRelayServerData(string ipv4Address, ushort port, byte[] allocatio
273
336
/// </summary>
274
337
public void SetConnectionData ( string ipv4Address , ushort port )
275
338
{
276
- m_ServerAddress = ipv4Address ;
277
- m_ServerPort = port ;
339
+ ConnectionData . Address = ipv4Address ;
340
+ ConnectionData . Port = port ;
341
+ }
342
+
343
+ /// <summary>
344
+ /// Sets IP and Port information. This will be ignored if using the Unity Relay and you should call <see cref="SetRelayServerData"/>
345
+ /// </summary>
346
+ public void SetConnectionData ( NetworkEndPoint endPoint )
347
+ {
348
+ ConnectionData = endPoint ;
278
349
}
279
350
280
351
private bool StartRelayServer ( )
@@ -372,25 +443,23 @@ private bool ProcessEvent()
372
443
373
444
private unsafe void ReadData ( int size , ref DataStreamReader reader , ref NetworkConnection networkConnection )
374
445
{
375
- if ( size > m_MessageBufferSize )
446
+ if ( size > m_SendQueueBatchSize )
376
447
{
377
- Debug . LogError ( "The received message does not fit into the message buffer" ) ;
448
+ Debug . LogError ( $ "The received message does not fit into the message buffer: { size } { m_SendQueueBatchSize } ") ;
378
449
}
379
450
else
380
451
{
381
452
unsafe
382
453
{
383
- fixed ( byte * buffer = & m_MessageBuffer [ 0 ] )
384
- {
385
- reader . ReadBytes ( buffer , size ) ;
386
- }
454
+ using var data = new NativeArray < byte > ( size , Allocator . Temp ) ;
455
+ reader . ReadBytes ( data ) ;
456
+
457
+ InvokeOnTransportEvent ( NetcodeNetworkEvent . Data ,
458
+ ParseClientId ( networkConnection ) ,
459
+ new ArraySegment < byte > ( data . ToArray ( ) , 0 , size ) ,
460
+ Time . realtimeSinceStartup
461
+ ) ;
387
462
}
388
-
389
- InvokeOnTransportEvent ( NetcodeNetworkEvent . Data ,
390
- ParseClientId ( networkConnection ) ,
391
- new ArraySegment < byte > ( m_MessageBuffer , 0 , size ) ,
392
- Time . realtimeSinceStartup
393
- ) ;
394
463
}
395
464
}
396
465
@@ -438,7 +507,6 @@ public override void DisconnectLocalClient()
438
507
439
508
m_State = State . Disconnected ;
440
509
441
-
442
510
// If we successfully disconnect we dispatch a local disconnect message
443
511
// this how uNET and other transports worked and so this is just keeping with the old behavior
444
512
// should be also noted on the client this will call shutdown on the NetworkManager and the Transport
@@ -491,23 +559,20 @@ public override void Initialize()
491
559
{
492
560
Debug . Assert ( sizeof ( ulong ) == UnsafeUtility . SizeOf < NetworkConnection > ( ) ,
493
561
"Netcode connection id size does not match UTP connection id size" ) ;
494
- Debug . Assert ( m_MessageBufferSize > 5 , "Message buffer size must be greater than 5" ) ;
562
+ Debug . Assert ( m_MaximumPacketSize > 5 , "Message buffer size must be greater than 5" ) ;
495
563
496
564
m_NetworkParameters = new List < INetworkParameter > ( ) ;
497
565
498
566
// If we want to be able to actually handle messages MaximumMessageLength bytes in
499
567
// size, we need to allow a bit more than that in FragmentationUtility since this needs
500
568
// to account for headers and such. 128 bytes is plenty enough for such overhead.
501
- var maxFragmentationCapacity = MaximumMessageLength + 128 ;
502
- m_NetworkParameters . Add ( new FragmentationUtility . Parameters ( ) { PayloadCapacity = maxFragmentationCapacity } ) ;
569
+ m_NetworkParameters . Add ( new FragmentationUtility . Parameters ( ) { PayloadCapacity = m_SendQueueBatchSize } ) ;
503
570
m_NetworkParameters . Add ( new BaselibNetworkParameter ( )
504
571
{
505
- maximumPayloadSize = ( uint ) m_MessageBufferSize ,
506
- receiveQueueCapacity = m_ReciveQueueSize ,
507
- sendQueueCapacity = m_SendQueueSize
572
+ maximumPayloadSize = ( uint ) m_MaximumPacketSize ,
573
+ receiveQueueCapacity = m_MaxPacketQueueSize ,
574
+ sendQueueCapacity = m_MaxPacketQueueSize
508
575
} ) ;
509
-
510
- m_MessageBuffer = new byte [ m_MessageBufferSize ] ;
511
576
}
512
577
513
578
public override NetcodeNetworkEvent PollEvent ( out ulong clientId , out ArraySegment < byte > payload , out float receiveTime )
@@ -556,7 +621,6 @@ private unsafe void SendBatchedMessage(ulong clientId, ref NativeArray<byte> dat
556
621
{
557
622
var payloadSize = data . Length + 1 ; // One extra byte to mark whether this message is batched or not
558
623
var result = m_Driver . BeginSend ( pipeline , ParseClientId ( clientId ) , out var writer , payloadSize ) ;
559
-
560
624
if ( result == 0 )
561
625
{
562
626
if ( data . IsCreated )
@@ -573,13 +637,14 @@ private unsafe void SendBatchedMessage(ulong clientId, ref NativeArray<byte> dat
573
637
}
574
638
}
575
639
576
- Debug . LogError ( $ "Error sending the message { result } ") ;
640
+ Debug . LogError ( $ "Error sending the message: { ErrorUtilities . ErrorToString ( ( Networking . Transport . Error . StatusCode ) result , clientId ) } ") ;
577
641
}
578
642
579
643
private unsafe void SendMessageInstantly ( ulong clientId , ArraySegment < byte > data , NetworkPipeline pipeline )
580
644
{
581
645
var payloadSize = data . Count + 1 + 4 ; // 1 byte to indicate if the message is batched and 4 for the payload size
582
646
var result = m_Driver . BeginSend ( pipeline , ParseClientId ( clientId ) , out var writer , payloadSize ) ;
647
+
583
648
if ( result == 0 )
584
649
{
585
650
if ( data . Array != null )
@@ -604,7 +669,7 @@ private unsafe void SendMessageInstantly(ulong clientId, ArraySegment<byte> data
604
669
}
605
670
}
606
671
607
- Debug . LogError ( $ "Error sending the message { result } ") ;
672
+ Debug . LogError ( $ "Error sending the message: { ErrorUtilities . ErrorToString ( ( Networking . Transport . Error . StatusCode ) result , clientId ) } ") ;
608
673
}
609
674
610
675
/// <summary>
@@ -657,7 +722,7 @@ public override bool StartServer()
657
722
switch ( m_ProtocolType )
658
723
{
659
724
case ProtocolType . UnityTransport :
660
- return ServerBindAndListen ( NetworkEndPoint . Parse ( m_ServerAddress , m_ServerPort ) ) ;
725
+ return ServerBindAndListen ( ConnectionData ) ;
661
726
case ProtocolType . RelayUnityTransport :
662
727
return StartRelayServer ( ) ;
663
728
default :
@@ -743,7 +808,6 @@ public void CreateDriver(UnityTransport transport, out NetworkDriver driver, out
743
808
}
744
809
}
745
810
746
-
747
811
// -------------- Utility Types -------------------------------------------------------------------------------
748
812
749
813
/// <summary>
0 commit comments