-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkClient.cs
555 lines (413 loc) · 20.7 KB
/
NetworkClient.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
// This file is provided under The MIT License as part of SqualiveNetworking.
// Copyright (c) Squalive-Studios
// For additional information please see the included LICENSE.md file or view it on GitHub:
// https://github.com/Squalive/SqualiveNetworking
using Unity.Burst;
using System;
using System.Collections.Generic;
using AOT;
using SqualiveNetworking.Message;
using SqualiveNetworking.Message.Handler;
using SqualiveNetworking.Message.Processor;
using SqualiveNetworking.Tick;
using SqualiveNetworking.Utils;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Networking.Transport;
using Unity.Networking.Transport.Error;
using UnityEngine;
namespace SqualiveNetworking
{
public struct ClientDisconnectedArgs
{
public ushort ClientID;
public DisconnectReason Reason;
}
public struct ClientConnectedArgs
{
public ushort ClientID;
public byte IsLocal;
}
public delegate void ClientDisconnectedCallback( ref ClientDisconnectedArgs args );
public delegate void ClientConnectedCallback( ref ClientConnectedArgs args );
public static class NetworkClient
{
public static bool Initialized => _driver.IsCreated && _initialized && _connections.IsCreated;
private static NetworkDriver _driver;
private static NativeArray<NetworkConnection> _connections;
private static NetworkConnection Connection => _connections[ 0 ];
private static NativeNetworkMessageHandlers _internalHandlers;
private static NativeNetworkMessageHandlers _customHandlers;
private static NetworkPipeline _fragmentationPipeline, _reliablePipeline, _unreliablePipeline;
private static JobHandle _clientJobHandle;
private static bool _initialized;
private static PortableFunctionPointer<ClientDisconnectedCallback> _clientDisconnectedPtr;
private static PortableFunctionPointer<ClientConnectedCallback> _clientConnectedPtr;
private static PortableFunctionPointer<MessageReceivedCallback> _messageReceivedPtr;
private static MessageProcessorHandler _messageProcessorHandler;
private static NativeHashMap<byte, MessageProcessor> _processors;
internal static readonly SharedStatic<ushort> SharedClientID = SharedStatic<ushort>.GetOrCreate<ClientIDKey>( );
internal static readonly SharedStatic<TickSystem> TickSystem = SharedStatic<TickSystem>.GetOrCreate<TickKey>( );
public static ushort ClientID => SharedClientID.Data;
public static bool IsConnected => ClientID != 0 ;
public static uint CurrentTick => TickSystem.Data.CurrentTick;
private class ClientKey { }
private class ClientIDKey { }
private class TickKey { }
public static bool EnsureInitialized()
{
if ( !_initialized )
{
#if ENABLE_SQUALIVE_NET_DEBUG
throw new Exception( "Client hasn't been initialized" );
#endif
return false;
}
return true;
}
public static bool EnsureUnInitialized()
{
if ( _initialized )
{
#if ENABLE_SQUALIVE_NET_DEBUG
throw new Exception( "Client has been initialized already" );
#endif
return false;
}
return true;
}
public static void Initialize( TickSystem tickSystem, NetworkSettings settings, int connectionTimeoutMS = 1000, int maxConnectAttempts = 5 )
{
if ( !EnsureUnInitialized() )
return;
_initialized = true;
TickSystem.Data = tickSystem;
SharedClientID.Data = 0;
settings = settings.WithNetworkConfigParameters( 1000, 5 );
_driver = NetworkDriver.Create( settings );
_connections = new NativeArray<NetworkConnection>( 1, Allocator.Persistent );
_connections[ 0 ] = default;
_internalHandlers = new NativeNetworkMessageHandlers( Allocator.Persistent );
_customHandlers = new NativeNetworkMessageHandlers( Allocator.Persistent );
// Add internal messages layers
_internalHandlers.AddLayer( new ClientConnectedNativeMessageHandler() );
_fragmentationPipeline = _driver.CreatePipeline( typeof( FragmentationPipelineStage ) );
_reliablePipeline = _driver.CreatePipeline( typeof( ReliableSequencedPipelineStage ) );
_unreliablePipeline = _driver.CreatePipeline( typeof( UnreliableSequencedPipelineStage ) );
_clientConnectedPtr = new PortableFunctionPointer<ClientConnectedCallback>( NetworkClientBurst.ClientConnected );
_messageProcessorHandler = new MessageProcessorHandler( 2, Allocator.Persistent );
_processors = new NativeHashMap<byte, MessageProcessor>( 32, Allocator.Persistent );
NetworkClientEvent.Initialize( );
}
public static void Initialize( TickSystem tickSystem, int connectionTimeoutMS = 1000,
int maxConnectAttempts = 5 ) => Initialize( tickSystem, new NetworkSettings( Allocator.Temp ),
connectionTimeoutMS, maxConnectAttempts );
public static void DeInitialize()
{
if ( !EnsureInitialized() )
return;
Disconnect();
_internalHandlers.Dispose();
_customHandlers.Dispose();
_connections.Dispose();
_driver.Dispose();
_messageProcessorHandler.Dispose();
_processors.Dispose();
#if ENABLE_SQUALIVE_NET_DEBUG
Debug.Log( "[CLIENT]: Disposing client...." );
#endif
_initialized = false;
NetworkClientEvent.DeInitialize();
}
public static bool Connect( string ipAddress, ushort port = 27015, NetworkFamily networkFamily = NetworkFamily.Ipv4 )
{
if ( !EnsureInitialized() )
return false;
var endPoint = NetworkEndpoint.Parse( ipAddress, port, networkFamily );
_connections[0] = _driver.Connect( endPoint );
return Connection != default;
}
public static bool ConnectToLocal( ushort port = 27015, bool ipv6 = false )
{
if ( !EnsureInitialized() )
return false;
_clientJobHandle.Complete();
var endPoint = ipv6 ? NetworkEndpoint.LoopbackIpv6 : NetworkEndpoint.LoopbackIpv4;
endPoint = endPoint.WithPort( port );
_connections[ 0 ] = _driver.Connect( endPoint );
return Connection != default;
}
public static void Disconnect()
{
if ( !EnsureInitialized() )
return;
SharedClientID.Data = 0;
_clientJobHandle.Complete();
Connection.Disconnect( _driver );
_driver.ScheduleUpdate().Complete();
#if ENABLE_SQUALIVE_NET_DEBUG
Debug.Log( "[CLIENT]: Disconnecting from server...." );
#endif
}
/// <summary>
/// Force an update which is highly unrecommended
/// </summary>
public static void Update()
{
if ( !EnsureInitialized() )
return;
_clientJobHandle.Complete();
NetworkClientEvent.ProcessEvents();
_clientJobHandle = _driver.ScheduleUpdate();
_clientJobHandle = new ClientUpdateJob
{
Driver = _driver,
Connections = _connections,
InstanceID = ClientID,
ClientDisconnectedPtr = _clientDisconnectedPtr,
ClientDisconnectedWriter = NetworkClientEvent.GetClientDisconnectedWriter(),
ClientConnectedPtr = _clientConnectedPtr,
ClientConnectedWriter = NetworkClientEvent.GetClientConnectedWriter(),
MessageReceivedCallback = _messageReceivedPtr,
MessageReceivedArgsWriter = NetworkClientEvent.GetMessageReceivedWriter(),
InternalMessageLayers = _internalHandlers.GetReadOnlyLayers(),
CustomMessageLayers = _customHandlers.GetReadOnlyLayers(),
MessageProcessorHandler = _messageProcessorHandler,
Processors = _processors.AsReadOnly(),
}.Schedule( _clientJobHandle );
}
public static void Tick( float deltaTime )
{
while ( TickSystem.Data.Update( ref deltaTime ) )
{
Update();
}
}
public static void SendMessage<T>( SendType sendType, MessageProcessor messageProcessor, T netMessage ) where T : unmanaged, INetMessage
{
DataStreamWriter writer;
switch ( sendType )
{
case SendType.Reliable:
if ( !NetworkHelper.BeginSend( _driver, _reliablePipeline, _messageProcessorHandler, messageProcessor, Connection, out writer ) ) return;
break;
case SendType.Frag:
if ( !NetworkHelper.BeginSend( _driver, _fragmentationPipeline, _messageProcessorHandler, messageProcessor, Connection, out writer ) ) return;
break;
default:
if ( !NetworkHelper.BeginSend( _driver, _unreliablePipeline, _messageProcessorHandler, messageProcessor, Connection, out writer ) ) return;
break;
}
NetworkHelper.SendCustomMessage( netMessage, _driver, ref writer );
}
public static void SendMessage<T>( SendType sendType, T netMessage ) where T : unmanaged, INetMessage
{
SendMessage( sendType, MessageProcessor.Null, netMessage );
}
public static void SetClientDisconnectedPtr( ClientDisconnectedCallback callback )
{
_clientDisconnectedPtr = new PortableFunctionPointer<ClientDisconnectedCallback>( callback );
}
public static void SetMessageReceivedFunctionPtr( MessageReceivedCallback callback )
{
_messageReceivedPtr = new PortableFunctionPointer<MessageReceivedCallback>( callback );
}
public static void AddNativeMessageHandler<T>( T layer ) where T : unmanaged, INativeMessageHandler
{
_customHandlers.AddLayer( layer );
}
public static MessageProcessor CreateProcessor<T> ( T[] processorInterface ) where T : IMessageProcessorStage
{
var processor = _messageProcessorHandler.CreateProcessor( processorInterface );
_processors.TryAdd( processor.InternalID, processor );
return processor;
}
#if ENABLE_SQUALIVE_NET_BURST
[BurstCompile]
#endif
internal unsafe struct ClientUpdateJob : IJob
{
public NetworkDriver Driver;
public NativeArray<NetworkConnection> Connections;
public PortableFunctionPointer<ClientDisconnectedCallback> ClientDisconnectedPtr;
[NativeDisableContainerSafetyRestriction]
public NativeQueue<ClientDisconnectedArgs>.ParallelWriter ClientDisconnectedWriter;
public PortableFunctionPointer<ClientConnectedCallback> ClientConnectedPtr;
[NativeDisableContainerSafetyRestriction]
public NativeQueue<ClientConnectedArgs>.ParallelWriter ClientConnectedWriter;
// Use for triggering message received function ptr
public PortableFunctionPointer<MessageReceivedCallback> MessageReceivedCallback;
[NativeDisableContainerSafetyRestriction]
public NativeQueue<MessageReceivedPtr>.ParallelWriter MessageReceivedArgsWriter;
public NativeArray<NativeMessageHandler>.ReadOnly InternalMessageLayers;
public NativeArray<NativeMessageHandler>.ReadOnly CustomMessageLayers;
public MessageProcessorHandler MessageProcessorHandler;
public NativeHashMap<byte, MessageProcessor>.ReadOnly Processors;
public ushort InstanceID;
public void Execute()
{
if ( !Connections[ 0 ].IsCreated )
return;
DataStreamReader stream;
NetworkEvent.Type cmd;
while ( ( cmd = Connections[ 0 ].PopEvent( Driver, out stream ) ) != NetworkEvent.Type.Empty )
{
switch ( cmd )
{
#if ENABLE_SQUALIVE_NET_DEBUG
case NetworkEvent.Type.Connect:
Debug.Log( $"[CLIENT]: Successfully Connected to {Driver.GetRemoteEndpoint( Connections[ 0 ] ).ToFixedString()}" );
break;
#endif
case NetworkEvent.Type.Disconnect:
var reason = (DisconnectReason)stream.ReadByte();
#if ENABLE_SQUALIVE_NET_DEBUG
Debug.Log(
$"[CLIENT]: Disconnected from {Driver.GetRemoteEndpoint( Connections[ 0 ] ).ToFixedString()} {reason.ToFixedString()}" );
#endif
var args = new ClientDisconnectedArgs
{
ClientID = InstanceID,
Reason = reason,
};
if ( ClientDisconnectedPtr.IsCreated )
{
ClientDisconnectedPtr.Ptr.Invoke( ref args );
}
ClientDisconnectedWriter.Enqueue( args );
Connections[ 0 ] = default;
break;
case NetworkEvent.Type.Data:
var streamPtr = stream.GetUnsafeReadOnlyPtr();
var streamLength = stream.Length;
var processorInternalID = stream.ReadByte();
var processor = MessageProcessor.Null;
byte hasProcessorOutput = 0;
void* processorOutput = default;
if ( processorInternalID > 0 && Processors.TryGetValue( processorInternalID, out processor ) )
{
hasProcessorOutput = MessageProcessorHandler.ProcessRead( processor, ref stream, out processorOutput ) ? StreamExtensions.True : StreamExtensions.False;
}
var type = stream.ReadByte();
var messageID = stream.ReadUShort();
var ptr = UnsafeUtility.AddressOf( ref this );
// Trigger message handler here
var messageReceivedArgs = new MessageReceivedArgs
{
Connection = Connections[ 0 ],
MessageID = messageID,
Stream = stream,
Processor = processor,
HasProcessorOutput = hasProcessorOutput,
ProcessorOutputPtr = processorOutput,
};
switch ( type )
{
// Internal
case 0:
ProcessMessageLayers( ref messageReceivedArgs, ref InternalMessageLayers, ptr );
break;
// Custom
case 1:
var messageReceivedPtr = new MessageReceivedPtr
{
Args = messageReceivedArgs,
StreamPtr = streamPtr,
Length = streamLength,
BytesRead = stream.GetBytesRead(),
};
MessageReceivedArgsWriter.Enqueue( messageReceivedPtr );
if ( MessageReceivedCallback.IsCreated )
{
MessageReceivedCallback.Ptr.Invoke( ref messageReceivedArgs );
}
ProcessMessageLayers( ref messageReceivedArgs, ref CustomMessageLayers, ptr );
break;
}
break;
}
}
}
private void ProcessMessageLayers( ref MessageReceivedArgs args, ref NativeArray<NativeMessageHandler>.ReadOnly layers, void* ptr )
{
bool executed = false;
for ( int i = 0; i < layers.Length; i++ )
{
var layer = layers[ i ];
if ( layer.IsCreated && layer.CompatibleMessageID == args.MessageID )
{
layer.ProcessFunction.Ptr.Invoke( ref args, ptr );
executed = true;
}
}
if ( !executed )
return;
if ( !args.HasProcessorOutput.ToBoolean() )
return;
// Free memory is we are done with it
UnsafeUtility.Free( args.ProcessorOutputPtr, Allocator.Temp );
}
}
}
/// <summary>
/// Use this for internal bursted event handling
/// </summary>
[BurstCompile]
internal static class NetworkClientBurst
{
[BurstCompile]
[MonoPInvokeCallback(typeof(ClientConnectedCallback))]
public static void ClientConnected( ref ClientConnectedArgs args )
{
if ( args.IsLocal.ToBoolean() )
{
NetworkClient.SharedClientID.Data = args.ClientID;
}
}
}
public static class NetworkClientEvent
{
public static event ClientDisconnectedCallback ClientDisconnected;
public static event ClientConnectedCallback ClientConnected;
public static MessageReceivedCallback MessageReceived
{
get => _messageHandler.MessageReceived;
set => _messageHandler.MessageReceived = value;
}
private static MessageHandler _messageHandler;
private static NativeQueue<ClientDisconnectedArgs> _clientDisconnectedArgs;
private static NativeQueue<ClientConnectedArgs> _clientConnectedArgs;
internal static void Initialize()
{
_clientDisconnectedArgs = new NativeQueue<ClientDisconnectedArgs>( Allocator.Persistent );
_clientConnectedArgs = new NativeQueue<ClientConnectedArgs>( Allocator.Persistent );
_messageHandler = new MessageHandler( "CLIENT", Allocator.Persistent );
}
internal static void DeInitialize()
{
_clientDisconnectedArgs.Dispose();
_clientConnectedArgs.Dispose();
_messageHandler.Dispose();
}
internal static void ProcessEvents()
{
while ( _clientDisconnectedArgs.TryDequeue( out var args ) )
{
ClientDisconnected?.Invoke( ref args );
}
while ( _clientConnectedArgs.TryDequeue( out var args ) )
{
ClientConnected?.Invoke( ref args );
}
_messageHandler.Update();
}
public static void AddManagedReceivedCallback( ushort messageID, MessageReceivedCallback receivedCallback )
{
_messageHandler.AddManagedReceivedCallback( messageID, receivedCallback );
}
internal static NativeQueue<ClientDisconnectedArgs>.ParallelWriter GetClientDisconnectedWriter() => _clientDisconnectedArgs.AsParallelWriter();
internal static NativeQueue<ClientConnectedArgs>.ParallelWriter GetClientConnectedWriter() => _clientConnectedArgs.AsParallelWriter();
internal static NativeQueue<MessageReceivedPtr>.ParallelWriter GetMessageReceivedWriter() => _messageHandler.AsParallelWriter();
}
}