diff --git a/README.md b/README.md index cf4e29c..dba43d7 100644 --- a/README.md +++ b/README.md @@ -61,8 +61,8 @@ class UdpServer : UdpServerEapBase } /// - public UdpServer(ushort maxClients, ushort maxPacketSize = 65522) - : base(maxClients, maxPacketSize) { } + public UdpServer(ushort maxPacketSize = 65522) + : base(maxPacketSize) { } } class UdpServerClient : UdpServerClientBase @@ -74,7 +74,7 @@ class UdpServerClient : UdpServerClientBase ```csharp static void Main(string[] args) { - using(UdpServer server = new UdpServer(32)) + using(UdpServer server = new UdpServer()) { server.ClientConnected += (server1, client) => { @@ -154,8 +154,8 @@ class TcpServer : TcpServerEapBase return true; } - public TcpServer(ushort expectedMaxClient = 32, ushort maxPacketSize = 65520) - : base(expectedMaxClient, maxPacketSize) { } + public TcpServer(ushort maxPacketSize = 65520) + : base(maxPacketSize) { } } class TcpServerClient : TcpServerClientBase @@ -188,7 +188,7 @@ static void Main(string[] args) string request = (string)data; Console.WriteLine($"Request: {request}"); byte[] buffer = Encoding.UTF8.GetBytes(DateTime.Now.ToLongDateString()); - server1.SendTo(client, 45, buffer, 0, buffer.Length, responseid); + server1.SendTo(client, responseid, buffer, 0, buffer.Length, true); return true; }); diff --git a/examples/Example.Client/Program.cs b/examples/Example.Client/Program.cs index 5c615d8..f2e719e 100644 --- a/examples/Example.Client/Program.cs +++ b/examples/Example.Client/Program.cs @@ -35,7 +35,7 @@ private static void Main(string[] args) #endif client.Disconnected += (c, r) => { Console.WriteLine(r + " | Disconnected"); }; - client.AddCommand(DeserializePacketToString, 1); + client.AddCommand(1, DeserializePacketToString); client.AddDataReceivedCallback( 1, (client1, data, responseID) => @@ -62,13 +62,14 @@ private static string DeserializePacketToString(in Packet packet) return Encoding.UTF8.GetString(packet.Buffer, packet.Offset, packet.Length); } - private static async void SendRequestAndWaitForResponse(IClient client, string data, uint responseID) + private static async void SendRequestAndWaitForResponse(IClient client, string data, ushort responseID) { byte[] response = Encoding.UTF8.GetBytes(data + "World " + string.Join(", ", Enumerable.Range(1, 1_000_000))); Response result = await client.SendR( responseID, response, 0, response.Length, DeserializePacketToString, true); - Console.WriteLine("GOT: {0}", result.Result); + + Console.WriteLine("GOT({1}): {0}", result.Result, result.SendError); } } } \ No newline at end of file diff --git a/examples/Example.Server/Program.cs b/examples/Example.Server/Program.cs index f19b64b..2fb748d 100644 --- a/examples/Example.Server/Program.cs +++ b/examples/Example.Server/Program.cs @@ -52,7 +52,7 @@ private static async void SendRequestAndWaitForResponse(IServer se byte[] request = Encoding.UTF8.GetBytes("Hello "); Response response = await server.SendToR( client, 1, request, 0, request.Length, DeserializePacketToString); - Console.WriteLine("GOT: {0}", response.Result); + Console.WriteLine("GOT({1}): {0}", response.Result, response.SendError); byte[] requestResponse = Encoding.UTF8.GetBytes($"Current server time is: {DateTime.UtcNow}"); server.SendTo(client, response.ID, requestResponse, 0, requestResponse.Length, true); @@ -70,8 +70,8 @@ class Server : TcpServerEapBase class Server : UdpServerEapBase #endif { - public Server(ushort expectedMaxClient = 32, ushort expectedMaxPayloadSize = 512) - : base(expectedMaxClient, expectedMaxPayloadSize) { } + public Server(ushort expectedMaxPayloadSize = 512) + : base(expectedMaxPayloadSize) { } protected override bool CreateServerClient(out ServerClient serverClient) { diff --git a/src/Exomia.Network/BigDataHandler.cs b/src/Exomia.Network/BigDataHandler.cs index 3ca9a3e..97af2c8 100644 --- a/src/Exomia.Network/BigDataHandler.cs +++ b/src/Exomia.Network/BigDataHandler.cs @@ -18,10 +18,6 @@ namespace Exomia.Network { - /// - /// A big data handler. - /// - /// Type of the key. abstract class BigDataHandler : IDisposable where TKey : struct { private readonly Dictionary _bigDataBuffers; @@ -179,7 +175,7 @@ internal override int AddBytes(int count) { int bytes = base.AddBytes(count); if (bytes == 0) { _timer.Dispose(); } - if (bytes != 0) { _timer.Change(TIMER_INTERVAL, Timeout.Infinite); } + else { _timer.Change(TIMER_INTERVAL, Timeout.Infinite); } return bytes; } } diff --git a/src/Exomia.Network/Buffers/ByteArrayPool.cs b/src/Exomia.Network/Buffers/ByteArrayPool.cs index 784c891..c85ee8c 100644 --- a/src/Exomia.Network/Buffers/ByteArrayPool.cs +++ b/src/Exomia.Network/Buffers/ByteArrayPool.cs @@ -16,11 +16,11 @@ namespace Exomia.Network.Buffers { static class ByteArrayPool { - private static SpinLock s_lock; - private static readonly byte[]?[][] s_buffers; - private static readonly uint[] s_index; - private static readonly int[] s_bufferLength; - private static readonly int[] s_bufferCount; + private static SpinLock s_lock; + private static readonly byte[]?[]?[] s_buffers; + private static readonly uint[] s_index; + private static readonly int[] s_bufferLength; + private static readonly int[] s_bufferCount; /// /// Initializes static members of the class. @@ -52,16 +52,13 @@ internal static byte[] Rent(int size) { s_lock.Enter(ref lockTaken); - if (s_buffers[bucketIndex] == null) - { - s_buffers[bucketIndex] = new byte[s_bufferCount[bucketIndex]][]; - } + s_buffers[bucketIndex] ??= new byte[s_bufferCount[bucketIndex]][]; - if (s_index[bucketIndex] < s_buffers[bucketIndex].Length) + if (s_index[bucketIndex] < s_buffers[bucketIndex]!.Length) { uint index = s_index[bucketIndex]++; - buffer = s_buffers[bucketIndex][index]; - s_buffers[bucketIndex][index] = null; + buffer = s_buffers[bucketIndex]![index]; + s_buffers[bucketIndex]![index] = null; } return buffer ?? new byte[s_bufferLength[bucketIndex]]; } @@ -86,7 +83,7 @@ internal static void Return(byte[] array) if (s_index[bucketIndex] != 0) { - s_buffers[bucketIndex][--s_index[bucketIndex]] = array; + s_buffers[bucketIndex]![--s_index[bucketIndex]] = array; } } finally diff --git a/src/Exomia.Network/ClientBase.Send.cs b/src/Exomia.Network/ClientBase.Send.cs index 0afe18b..bc6fe58 100644 --- a/src/Exomia.Network/ClientBase.Send.cs +++ b/src/Exomia.Network/ClientBase.Send.cs @@ -24,33 +24,33 @@ namespace Exomia.Network public abstract partial class ClientBase { /// - public SendError Send(uint commandOrResponseID, byte[] data, int offset, int length, bool isResponse = false) + public SendError Send(ushort commandOrResponseID, byte[] data, int offset, int length, bool isResponse = false) { return BeginSend(commandOrResponseID, data, offset, length, 0, isResponse); } /// - public SendError Send(uint commandOrResponseID, byte[] data, bool isResponse = false) + public SendError Send(ushort commandOrResponseID, byte[] data, bool isResponse = false) { return BeginSend(commandOrResponseID, data, 0, data.Length, 0, isResponse); } /// - public SendError Send(uint commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged + public SendError Send(ushort commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged { data.ToBytesUnsafe2(out byte[] dataB, out int length); return BeginSend(commandOrResponseID, dataB, 0, length, 0, isResponse); } /// - public SendError Send(uint commandOrResponseID, ISerializable serializable, bool isResponse = false) + public SendError Send(ushort commandOrResponseID, ISerializable serializable, bool isResponse = false) { byte[] dataB = serializable.Serialize(out int length); return BeginSend(commandOrResponseID, dataB, 0, length, 0, isResponse); } /// - public async Task> SendR(uint commandOrResponseID, + public async Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -58,10 +58,10 @@ public async Task> SendR(uint TimeSpan timeout, bool isResponse = false) { - TaskCompletionSource<(uint requestID, Packet packet)> tcs = - new TaskCompletionSource<(uint, Packet)>(TaskCreationOptions.None); + TaskCompletionSource<(ushort requestID, Packet packet)> tcs = + new TaskCompletionSource<(ushort, Packet)>(TaskCreationOptions.None); using CancellationTokenSource cts = new CancellationTokenSource(timeout); - uint requestID; + ushort requestID; bool lockTaken = false; try { @@ -92,7 +92,7 @@ public async Task> SendR(uint SendError sendError = BeginSend(commandOrResponseID, data, offset, length, requestID, isResponse); if (sendError == SendError.None) { - (uint rID, Packet packet) = await tcs.Task; + (ushort rID, Packet packet) = await tcs.Task; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (packet.Buffer != null) @@ -121,7 +121,7 @@ public async Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, byte[] data, bool isResponse = false) + public Task> SendR(ushort commandOrResponseID, byte[] data, bool isResponse = false) where TResult : unmanaged { return SendR( @@ -129,7 +129,7 @@ public Task> SendR(uint commandOrResponseID, byte[] d } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -141,7 +141,7 @@ public Task> SendR(uint commandOrResponseID, } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -152,7 +152,7 @@ public Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, bool isResponse = false) @@ -161,7 +161,7 @@ public Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -173,7 +173,7 @@ public Task> SendR(uint commandOrResponseID, } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, byte[] data, TimeSpan timeout, bool isResponse = false) @@ -183,7 +183,7 @@ public Task> SendR(uint commandOrResponseID, } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -193,7 +193,7 @@ public Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, ISerializable serializable, bool isResponse = false) where TResult : unmanaged @@ -204,7 +204,7 @@ public Task> SendR(uint commandOrResponseID, } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, bool isResponse = false) @@ -214,7 +214,7 @@ public Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, ISerializable serializable, TimeSpan timeout, bool isResponse = false) @@ -225,7 +225,7 @@ public Task> SendR(uint commandOrResponseID, } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -236,7 +236,7 @@ public Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, in T data, bool isResponse = false) + public Task> SendR(ushort commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged where TResult : unmanaged { @@ -246,7 +246,7 @@ public Task> SendR(uint commandOrResponseID, in T } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, in T data, DeserializePacketHandler deserialize, bool isResponse = false) @@ -257,7 +257,7 @@ public Task> SendR(uint } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, in T data, TimeSpan timeout, bool isResponse = false) @@ -269,7 +269,7 @@ public Task> SendR(uint commandOrResponseID, } /// - public Task> SendR(uint commandOrResponseID, + public Task> SendR(ushort commandOrResponseID, in T data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -320,11 +320,11 @@ private static TResult DeserializeResponse(in Packet packet) /// A SendError. /// /// Thrown when one or more arguments are outside the required range. - private unsafe SendError BeginSend(uint commandOrResponseID, + private unsafe SendError BeginSend(ushort commandOrResponseID, byte[] data, int offset, int length, - uint requestID, + ushort requestID, bool isResponse) { if (_clientSocket == null || (_state & SEND_FLAG) != SEND_FLAG) { return SendError.Invalid; } diff --git a/src/Exomia.Network/ClientBase.cs b/src/Exomia.Network/ClientBase.cs index d9c9bbd..22486d7 100644 --- a/src/Exomia.Network/ClientBase.cs +++ b/src/Exomia.Network/ClientBase.cs @@ -69,17 +69,20 @@ public event CommandDataReceivedHandler DataReceived private protected EncryptionMode _encryptionMode = EncryptionMode.None; private readonly byte[] _connectChecksum = new byte[16]; - private readonly ManualResetEvent _manuelResetEvent; - private readonly Dictionary _dataReceivedCallbacks; - private readonly Dictionary> _taskCompletionSources; - private readonly byte _listenerCount; + private readonly ManualResetEvent _manuelResetEvent; + private readonly Dictionary _dataReceivedCallbacks; + + private readonly Dictionary> + _taskCompletionSources; + + private readonly byte _listenerCount; private readonly Event _dataReceived; - private SpinLock _dataReceivedCallbacksLock; - private SpinLock _lockTaskCompletionSources; - private int _port; - private string _serverAddress; - private uint _requestID; - private int _packetID; + private SpinLock _dataReceivedCallbacksLock; + private SpinLock _lockTaskCompletionSources; + private int _port; + private string _serverAddress; + private ushort _requestID; + private int _packetID; /// /// Gets the port. @@ -224,9 +227,9 @@ public bool NoDelay private protected ClientBase(byte listenerCount = 1) { _listenerCount = listenerCount; - _dataReceivedCallbacks = new Dictionary(INITIAL_QUEUE_SIZE); + _dataReceivedCallbacks = new Dictionary(INITIAL_QUEUE_SIZE); _taskCompletionSources = - new Dictionary>(INITIAL_TASK_COMPLETION_QUEUE_SIZE); + new Dictionary>(INITIAL_TASK_COMPLETION_QUEUE_SIZE); _dataReceivedCallbacksLock = new SpinLock(Debugger.IsAttached); _lockTaskCompletionSources = new SpinLock(Debugger.IsAttached); @@ -369,13 +372,13 @@ private protected void Disconnect(DisconnectReason reason) private protected unsafe void DeserializeData(in DeserializePacketInfo deserializePacketInfo) { - uint commandOrResponseID = deserializePacketInfo.CommandOrResponseID; - uint requestID = deserializePacketInfo.RequestID; + ushort commandOrResponseID = deserializePacketInfo.CommandOrResponseID; + ushort requestID = deserializePacketInfo.RequestID; if (deserializePacketInfo.IsResponseBitSet) { - TaskCompletionSource<(uint, Packet)>? cs; - bool lockTaken = false; + TaskCompletionSource<(ushort, Packet)>? cs; + bool lockTaken = false; try { _lockTaskCompletionSources.Enter(ref lockTaken); @@ -453,23 +456,33 @@ private protected unsafe void DeserializeData(in DeserializePacketInfo deseriali #region Add & Remove + /// + /// add a command deserializer. + /// + /// Identifier for the command. + /// The deserialize handler. + public void AddCommand(ushort commandID, DeserializePacketHandler deserialize) + { + AddCommand(new[] { commandID }, deserialize); + } + /// /// add commands deserializers. /// + /// The command ids. /// The deserialize handler. - /// A variable-length parameters list containing command ids. /// Thrown when one or more required arguments are null. /// Thrown when one or more arguments are outside the required range. - public void AddCommand(DeserializePacketHandler deserialize, params uint[] commandIDs) + public void AddCommand(ushort[] commandIDs, DeserializePacketHandler deserialize) { - if (commandIDs.Length <= 0) { throw new ArgumentNullException(nameof(commandIDs)); } + if (commandIDs == null || commandIDs.Length <= 0) { throw new ArgumentNullException(nameof(commandIDs)); } bool lockTaken = false; try { _dataReceivedCallbacksLock.Enter(ref lockTaken); - foreach (uint commandID in commandIDs) + foreach (ushort commandID in commandIDs) { if (commandID > Constants.USER_COMMAND_LIMIT) { @@ -498,7 +511,7 @@ public void AddCommand(DeserializePacketHandler deserialize, params uint /// True if at least one command is removed, false otherwise. /// /// Thrown when one or more arguments are outside the required range. - public bool RemoveCommands(params uint[] commandIDs) + public bool RemoveCommands(params ushort[] commandIDs) { if (commandIDs.Length <= 0) { throw new ArgumentNullException(nameof(commandIDs)); } bool removed = false; @@ -506,7 +519,7 @@ public bool RemoveCommands(params uint[] commandIDs) try { _dataReceivedCallbacksLock.Enter(ref lockTaken); - foreach (uint commandID in commandIDs) + foreach (ushort commandID in commandIDs) { if (commandID > Constants.USER_COMMAND_LIMIT) { @@ -531,7 +544,7 @@ public bool RemoveCommands(params uint[] commandIDs) /// Thrown when one or more arguments are outside the required range. /// Thrown when one or more required arguments are null. /// Thrown when an exception error condition occurs. - public void AddDataReceivedCallback(uint commandID, DataReceivedHandler callback) + public void AddDataReceivedCallback(ushort commandID, DataReceivedHandler callback) { if (commandID > Constants.USER_COMMAND_LIMIT) { @@ -566,7 +579,7 @@ public void AddDataReceivedCallback(uint commandID, DataReceivedHandler callback /// The callback. /// Thrown when one or more arguments are outside the required range. /// Thrown when one or more required arguments are null. - public void RemoveDataReceivedCallback(uint commandID, DataReceivedHandler callback) + public void RemoveDataReceivedCallback(ushort commandID, DataReceivedHandler callback) { if (commandID > Constants.USER_COMMAND_LIMIT) { diff --git a/src/Exomia.Network/ClientDataReceivedHandler.cs b/src/Exomia.Network/ClientDataReceivedHandler.cs index 4be79f7..7ae6710 100644 --- a/src/Exomia.Network/ClientDataReceivedHandler.cs +++ b/src/Exomia.Network/ClientDataReceivedHandler.cs @@ -24,9 +24,9 @@ namespace Exomia.Network /// public delegate bool ClientCommandDataReceivedHandler(IServer server, TServerClient client, - uint commandID, + ushort commandID, object data, - uint responseID) + ushort responseID) where TServerClient : IServerClient; /// @@ -43,6 +43,6 @@ public delegate bool ClientCommandDataReceivedHandler(IServer(IServer server, TServerClient client, object data, - uint responseID) + ushort responseID) where TServerClient : IServerClient; } \ No newline at end of file diff --git a/src/Exomia.Network/CommandID.cs b/src/Exomia.Network/CommandID.cs index abbb46f..a08b1c6 100644 --- a/src/Exomia.Network/CommandID.cs +++ b/src/Exomia.Network/CommandID.cs @@ -18,16 +18,16 @@ static class CommandID /// /// CONNECT_ID. /// - public const uint CONNECT = 65534; + public const ushort CONNECT = 65534; /// /// DISCONNECT_ID. /// - public const uint DISCONNECT = 65533; + public const ushort DISCONNECT = 65533; /// /// PING_ID. /// - public const uint PING = 65532; + public const ushort PING = 65532; } } \ No newline at end of file diff --git a/src/Exomia.Network/Constants.cs b/src/Exomia.Network/Constants.cs index 2cc295a..0586a0d 100644 --- a/src/Exomia.Network/Constants.cs +++ b/src/Exomia.Network/Constants.cs @@ -10,29 +10,35 @@ namespace Exomia.Network { - /// - /// A constants. - /// static class Constants { - internal const int SAFETY_PAYLOAD_OFFSET = 20; - internal const int TCP_HEADER_SIZE = 7; - internal const int TCP_HEADER_OFFSET = TCP_HEADER_SIZE + SAFETY_PAYLOAD_OFFSET; - internal const ushort TCP_PAYLOAD_SIZE_MAX = 65535 - TCP_HEADER_OFFSET - 1 - 8189; - internal const int UDP_HEADER_SIZE = 5; - internal const int UDP_HEADER_OFFSET = UDP_HEADER_SIZE + SAFETY_PAYLOAD_OFFSET; - internal const ushort UDP_PAYLOAD_SIZE_MAX = 65507 - UDP_HEADER_OFFSET; - internal const uint USER_COMMAND_LIMIT = 65500; - internal const int COMMAND_OR_RESPONSE_ID_SHIFT = 16; - internal const int DATA_LENGTH_MASK = 0xFFFF; - internal const int LENGTH_THRESHOLD = 1 << 12; - internal const byte RESPONSE_1_BIT = 1 << 5; - internal const byte REQUEST_1_BIT = 1 << 6; - internal const byte IS_CHUNKED_1_BIT = 1 << 7; - internal const byte COMPRESSED_MODE_MASK = 0b0001_1000; - internal const uint RESPONSE_BIT_MASK = 0b0010_0000; - internal const uint REQUEST_BIT_MASK = 0b0100_0000; - internal const uint IS_CHUNKED_BIT_MASK = 0b1000_0000; - internal const byte ZERO_BYTE = 0; + // @formatter:off — disable formatter after this line + internal const ushort OFFSET_REQUEST_ID = 2; + internal const ushort OFFSET_COMPRESSION_MODE = 4; + internal const ushort OFFSET_CHUNK_INFO = 12; + + internal const int SAFETY_PAYLOAD_OFFSET = OFFSET_REQUEST_ID + + OFFSET_COMPRESSION_MODE + + OFFSET_CHUNK_INFO; + + private const ushort TCP_PAYLOAD_SIZE_MAX_ = 65535 - TCP_HEADER_OFFSET - 1; + private const ushort TCP_ENCODING_THRESHOLD = (TCP_PAYLOAD_SIZE_MAX_ / 8) + 1; + internal const int TCP_HEADER_SIZE = 7; + internal const int TCP_HEADER_OFFSET = TCP_HEADER_SIZE + SAFETY_PAYLOAD_OFFSET; + internal const ushort TCP_PAYLOAD_SIZE_MAX = TCP_PAYLOAD_SIZE_MAX_ - TCP_ENCODING_THRESHOLD; + + internal const int UDP_HEADER_SIZE = 5; + internal const int UDP_HEADER_OFFSET = UDP_HEADER_SIZE + SAFETY_PAYLOAD_OFFSET; + internal const ushort UDP_PAYLOAD_SIZE_MAX = 65507 - UDP_HEADER_OFFSET; + + internal const uint USER_COMMAND_LIMIT = 65500; + + internal const int LENGTH_THRESHOLD = 1 << 12; + internal const byte RESPONSE_1_BIT = 1 << 5; + internal const byte REQUEST_1_BIT = 1 << 6; + internal const byte IS_CHUNKED_1_BIT = 1 << 7; + internal const byte COMPRESSED_MODE_MASK = 0b0001_1000; + internal const byte ZERO_BYTE = 0; + // @formatter:on — enable formatter after this line } } \ No newline at end of file diff --git a/src/Exomia.Network/DataReceivedHandler.cs b/src/Exomia.Network/DataReceivedHandler.cs index 27fa66d..1a4f48b 100644 --- a/src/Exomia.Network/DataReceivedHandler.cs +++ b/src/Exomia.Network/DataReceivedHandler.cs @@ -20,7 +20,7 @@ namespace Exomia.Network /// /// true if you want to handle more data; false otherwise. /// - public delegate bool CommandDataReceivedHandler(IClient client, uint commandID, object data, uint responseID); + public delegate bool CommandDataReceivedHandler(IClient client, ushort commandID, object data, ushort responseID); /// /// Called than a client received data from the server. @@ -31,5 +31,5 @@ namespace Exomia.Network /// /// true if you want to handle more data; false otherwise. /// - public delegate bool DataReceivedHandler(IClient client, object data, uint responseID); + public delegate bool DataReceivedHandler(IClient client, object data, ushort responseID); } \ No newline at end of file diff --git a/src/Exomia.Network/DeserializePacketInfo.cs b/src/Exomia.Network/DeserializePacketInfo.cs index 830bf2a..eed9cf5 100644 --- a/src/Exomia.Network/DeserializePacketInfo.cs +++ b/src/Exomia.Network/DeserializePacketInfo.cs @@ -18,17 +18,17 @@ struct DeserializePacketInfo /// /// Identifier for the command or response. /// - public uint CommandOrResponseID; + public ushort CommandOrResponseID; /// - /// True if this object is response bit set. + /// Identifier for the request. /// - public bool IsResponseBitSet; + public ushort RequestID; /// - /// Identifier for the request. + /// True if this object is response bit set. /// - public uint RequestID; + public bool IsResponseBitSet; /// /// The data. diff --git a/src/Exomia.Network/IClient.cs b/src/Exomia.Network/IClient.cs index 3308f53..a95a861 100644 --- a/src/Exomia.Network/IClient.cs +++ b/src/Exomia.Network/IClient.cs @@ -64,7 +64,7 @@ bool Connect(IPAddress[] ipAddresses, /// /// SendError. /// - SendError Send(uint commandOrResponseID, byte[] data, int offset, int length, bool isResponse = false); + SendError Send(ushort commandOrResponseID, byte[] data, int offset, int length, bool isResponse = false); /// /// send data to the server. @@ -75,7 +75,7 @@ bool Connect(IPAddress[] ipAddresses, /// /// SendError. /// - SendError Send(uint commandOrResponseID, byte[] data, bool isResponse = false); + SendError Send(ushort commandOrResponseID, byte[] data, bool isResponse = false); /// /// send data to the server. @@ -86,7 +86,7 @@ bool Connect(IPAddress[] ipAddresses, /// /// SendError. /// - SendError Send(uint commandOrResponseID, ISerializable serializable, bool isResponse = false); + SendError Send(ushort commandOrResponseID, ISerializable serializable, bool isResponse = false); /// /// send data to the server. @@ -98,7 +98,7 @@ bool Connect(IPAddress[] ipAddresses, /// /// SendError. /// - SendError Send(uint commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged; + SendError Send(ushort commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged; /// /// send data to the server. @@ -112,7 +112,7 @@ bool Connect(IPAddress[] ipAddresses, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -129,7 +129,7 @@ Task> SendR(uint commandOrResponseID, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, byte[] data, bool isResponse = false) + Task> SendR(ushort commandOrResponseID, byte[] data, bool isResponse = false) where TResult : unmanaged; /// @@ -145,7 +145,7 @@ Task> SendR(uint commandOrResponseID, byte[] data, bo /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -163,7 +163,7 @@ Task> SendR(uint command /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, bool isResponse = false); @@ -181,7 +181,7 @@ Task> SendR(uint command /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -200,7 +200,7 @@ Task> SendR(uint commandOrResponseID, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, TimeSpan timeout, bool isResponse = false) @@ -220,7 +220,7 @@ Task> SendR(uint commandOrResponseID, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, int offset, int length, @@ -240,7 +240,7 @@ Task> SendR(uint command /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -256,7 +256,7 @@ Task> SendR(uint command /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, ISerializable serializable, bool isResponse = false) where TResult : unmanaged; @@ -272,7 +272,7 @@ Task> SendR(uint commandOrResponseID, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, bool isResponse = false); @@ -288,7 +288,7 @@ Task> SendR(uint command /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, ISerializable serializable, TimeSpan timeout, bool isResponse = false) @@ -306,7 +306,7 @@ Task> SendR(uint commandOrResponseID, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -323,7 +323,7 @@ Task> SendR(uint command /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, in T data, bool isResponse = false) + Task> SendR(ushort commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged where TResult : unmanaged; @@ -339,7 +339,7 @@ Task> SendR(uint commandOrResponseID, in T data, b /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, in T data, DeserializePacketHandler deserialize, bool isResponse = false) @@ -357,7 +357,7 @@ Task> SendR(uint comm /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, in T data, TimeSpan timeout, bool isResponse = false) @@ -377,7 +377,7 @@ Task> SendR(uint commandOrResponseID, /// /// task of Response{TResult} /// - Task> SendR(uint commandOrResponseID, + Task> SendR(ushort commandOrResponseID, in T data, DeserializePacketHandler deserialize, TimeSpan timeout, diff --git a/src/Exomia.Network/IServer.cs b/src/Exomia.Network/IServer.cs index d0e6bb0..5477be8 100644 --- a/src/Exomia.Network/IServer.cs +++ b/src/Exomia.Network/IServer.cs @@ -34,7 +34,7 @@ public interface IServer : IDisposable /// A SendError. /// SendError SendTo(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -50,7 +50,7 @@ SendError SendTo(TServerClient client, /// /// A SendError. /// - SendError SendTo(TServerClient client, uint commandOrResponseID, byte[] data, bool isResponse = false); + SendError SendTo(TServerClient client, ushort commandOrResponseID, byte[] data, bool isResponse = false); /// /// send data to the client. @@ -63,7 +63,7 @@ SendError SendTo(TServerClient client, /// A SendError. /// SendError SendTo(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, bool isResponse = false); @@ -78,7 +78,7 @@ SendError SendTo(TServerClient client, /// /// A SendError. /// - SendError SendTo(TServerClient client, uint commandOrResponseID, in T1 data, bool isResponse = false) + SendError SendTo(TServerClient client, ushort commandOrResponseID, in T1 data, bool isResponse = false) where T1 : unmanaged; /// @@ -95,7 +95,7 @@ SendError SendTo(TServerClient client, uint commandOrResponseID, in T1 data, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -114,7 +114,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, bool isResponse = false) where TResult : unmanaged; @@ -134,7 +134,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -154,7 +154,7 @@ Task> SendToR(TServerClient clien /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, bool isResponse = false); @@ -174,7 +174,7 @@ Task> SendToR(TServerClient clien /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -195,7 +195,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, TimeSpan timeout, bool isResponse = false) @@ -217,7 +217,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -239,7 +239,7 @@ Task> SendToR(TServerClient clien /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -257,7 +257,7 @@ Task> SendToR(TServerClient clien /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, bool isResponse = false) where TResult : unmanaged; @@ -275,7 +275,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, bool isResponse = false); @@ -293,7 +293,7 @@ Task> SendToR(TServerClient clien /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, TimeSpan timeout, bool isResponse = false) @@ -313,7 +313,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -332,7 +332,7 @@ Task> SendToR(TServerClient clien /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in T data, bool isResponse = false) where T : unmanaged @@ -352,7 +352,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in T data, DeserializePacketHandler deserialize, bool isResponse = false) @@ -372,7 +372,7 @@ Task> SendToR(TServerClient cl /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in T data, TimeSpan timeout, bool isResponse = false) @@ -394,7 +394,7 @@ Task> SendToR(TServerClient client, /// task of Response{TResult} /// Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in T data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -408,21 +408,21 @@ Task> SendToR(TServerClient cl /// The data. /// The offset. /// The length. - void SendToAll(uint commandOrResponseID, byte[] data, int offset, int length); + void SendToAll(ushort commandOrResponseID, byte[] data, int offset, int length); /// /// Sends data to all clients. /// /// Identifier for the command or response. /// The data. - void SendToAll(uint commandOrResponseID, byte[] data); + void SendToAll(ushort commandOrResponseID, byte[] data); /// /// Sends data to all clients. /// /// Identifier for the command or response. /// The serializable. - void SendToAll(uint commandOrResponseID, ISerializable serializable); + void SendToAll(ushort commandOrResponseID, ISerializable serializable); /// /// Sends data to all clients. @@ -430,6 +430,6 @@ Task> SendToR(TServerClient cl /// Generic type parameter. /// Identifier for the command or response. /// The data. - void SendToAll(uint commandOrResponseID, in T1 data) where T1 : unmanaged; + void SendToAll(ushort commandOrResponseID, in T1 data) where T1 : unmanaged; } } \ No newline at end of file diff --git a/src/Exomia.Network/Lib/ClientEventEntry.cs b/src/Exomia.Network/Lib/ClientEventEntry.cs index 7b268e5..88f3944 100644 --- a/src/Exomia.Network/Lib/ClientEventEntry.cs +++ b/src/Exomia.Network/Lib/ClientEventEntry.cs @@ -49,7 +49,7 @@ public void Remove(DataReceivedHandler callback) /// The client. /// The data. /// Identifier for the response. - public void Raise(IClient client, object data, uint responseID) + public void Raise(IClient client, object data, ushort responseID) { for (int i = _dataReceived.Count - 1; i >= 0; --i) { diff --git a/src/Exomia.Network/Lib/ServerClientEventEntry.cs b/src/Exomia.Network/Lib/ServerClientEventEntry.cs index 394d893..afac934 100644 --- a/src/Exomia.Network/Lib/ServerClientEventEntry.cs +++ b/src/Exomia.Network/Lib/ServerClientEventEntry.cs @@ -51,7 +51,7 @@ public void Remove(ClientDataReceivedHandler callback) /// The client. /// The data. /// The responseID. - public void Raise(IServer server, TServerClient client, object data, uint responseID) + public void Raise(IServer server, TServerClient client, object data, ushort responseID) { for (int i = _dataReceived.Count - 1; i >= 0; --i) { diff --git a/src/Exomia.Network/Native/CircularBuffer.cs b/src/Exomia.Network/Native/CircularBuffer.cs index 671293f..cf542ee 100644 --- a/src/Exomia.Network/Native/CircularBuffer.cs +++ b/src/Exomia.Network/Native/CircularBuffer.cs @@ -292,7 +292,7 @@ public bool PeekByte(int offset, out byte b) /// /// skip bytes. /// [out] The packet header. - /// [out] Identifier for the command. + /// [out] Identifier for the command or response. /// [out] Length of the data. /// [out] The checksum. /// @@ -300,7 +300,7 @@ public bool PeekByte(int offset, out byte b) /// public bool PeekHeader(int skip, out byte packetHeader, - out uint commandID, + out ushort commandOrResponseID, out int dataLength, out ushort checksum) { @@ -310,41 +310,37 @@ public bool PeekHeader(int skip, _lock.Enter(ref lockTaken); if (_count == 0 || _count < skip + Constants.TCP_HEADER_SIZE) { - commandID = 0; - dataLength = 0; - packetHeader = 0; - checksum = 0; + commandOrResponseID = 0; + dataLength = 0; + packetHeader = 0; + checksum = 0; return false; } if (_tail + skip + Constants.TCP_HEADER_SIZE < _capacity) { - packetHeader = *(_ptr + _tail + skip); - uint h2 = *(uint*)(_ptr + _tail + skip + 1); - commandID = h2 >> Constants.COMMAND_OR_RESPONSE_ID_SHIFT; - dataLength = (int)(h2 & Constants.DATA_LENGTH_MASK); - checksum = *(ushort*)(_ptr + _tail + skip + 5); + packetHeader = *(_ptr + _tail + skip); + commandOrResponseID = *(ushort*)(_ptr + _tail + skip + 1); + dataLength = *(ushort*)(_ptr + _tail + skip + 3); + checksum = *(ushort*)(_ptr + _tail + skip + 5); } else if (_tail + skip < _capacity) { packetHeader = *(_ptr + ((_tail + skip) & _mask)); - uint h2 = (uint)((*(_ptr + ((_tail + skip + 4) & _mask)) << 24) - | (*(_ptr + ((_tail + skip + 3) & _mask)) << 16) - | (*(_ptr + ((_tail + skip + 2) & _mask)) << 8) - | *(_ptr + ((_tail + skip + 1) & _mask))); - commandID = h2 >> Constants.COMMAND_OR_RESPONSE_ID_SHIFT; - dataLength = (int)(h2 & Constants.DATA_LENGTH_MASK); + commandOrResponseID = (ushort)((*(_ptr + ((_tail + skip + 2) & _mask)) << 8) + | *(_ptr + ((_tail + skip + 1) & _mask))); + dataLength = (ushort)((*(_ptr + ((_tail + skip + 4) & _mask)) << 8) + | *(_ptr + ((_tail + skip + 3) & _mask))); checksum = (ushort)( (*(_ptr + ((_tail + skip + 6) & _mask)) << 8) | *(_ptr + ((_tail + skip + 5) & _mask))); } else { - packetHeader = *(_ptr + ((_tail + skip) & _mask)); - uint h2 = *(uint*)(_ptr + ((_tail + skip + 1) & _mask)); - commandID = h2 >> Constants.COMMAND_OR_RESPONSE_ID_SHIFT; - dataLength = (int)(h2 & Constants.DATA_LENGTH_MASK); - checksum = *(ushort*)(_ptr + ((_tail + skip + 5) & _mask)); + packetHeader = *(_ptr + ((_tail + skip) & _mask)); + commandOrResponseID = *(ushort*)(_ptr + ((_tail + skip + 1) & _mask)); + dataLength = *(ushort*)(_ptr + ((_tail + skip + 3) & _mask)); + checksum = *(ushort*)(_ptr + ((_tail + skip + 5) & _mask)); } return true; diff --git a/src/Exomia.Network/PacketInfo.cs b/src/Exomia.Network/PacketInfo.cs index c6dfdab..2c6ecd4 100644 --- a/src/Exomia.Network/PacketInfo.cs +++ b/src/Exomia.Network/PacketInfo.cs @@ -16,8 +16,8 @@ namespace Exomia.Network unsafe struct PacketInfo { public int PacketID; - public uint CommandOrResponseID; - public uint RequestID; + public ushort CommandOrResponseID; + public ushort RequestID; public bool IsResponse; public byte* Src; public int ChunkLength; diff --git a/src/Exomia.Network/Response.cs b/src/Exomia.Network/Response.cs index 99db967..6e00cf4 100644 --- a/src/Exomia.Network/Response.cs +++ b/src/Exomia.Network/Response.cs @@ -22,7 +22,7 @@ public readonly struct Response /// ///

Specify this id instead of a command id in case you need to respond to a request.

///
- public readonly uint ID; + public readonly ushort ID; /// /// The result. @@ -40,7 +40,7 @@ public readonly struct Response /// The result. /// The result. /// The send error. - internal Response(in TResult result, uint responseID, SendError sendError) + internal Response(in TResult result, ushort responseID, SendError sendError) { Result = result; ID = responseID; diff --git a/src/Exomia.Network/Serialization/Serialization.Tcp.cs b/src/Exomia.Network/Serialization/Serialization.Tcp.cs index 4392237..357c673 100644 --- a/src/Exomia.Network/Serialization/Serialization.Tcp.cs +++ b/src/Exomia.Network/Serialization/Serialization.Tcp.cs @@ -54,16 +54,16 @@ internal static int SerializeTcp(in PacketInfo packetInfo, int offset = 0; if (packetInfo.RequestID != 0) { - *dst |= Constants.REQUEST_1_BIT; - *(uint*)(dst + Constants.TCP_HEADER_SIZE) = packetInfo.RequestID; - offset = 4; + *dst |= Constants.REQUEST_1_BIT; + *(ushort*)(dst + Constants.TCP_HEADER_SIZE) = packetInfo.RequestID; + offset = Constants.OFFSET_REQUEST_ID; } if (packetInfo.CompressionMode != CompressionMode.None) { *dst |= (byte)packetInfo.CompressionMode; *(int*)(dst + Constants.TCP_HEADER_SIZE + offset) = packetInfo.Length; - offset += 4; + offset += Constants.OFFSET_COMPRESSION_MODE; } if (packetInfo.IsChunked) @@ -72,16 +72,15 @@ internal static int SerializeTcp(in PacketInfo packetInfo, *(int*)(dst + Constants.TCP_HEADER_SIZE + offset) = packetInfo.PacketID; *(int*)(dst + Constants.TCP_HEADER_SIZE + offset + 4) = packetInfo.ChunkOffset; *(int*)(dst + Constants.TCP_HEADER_SIZE + offset + 8) = packetInfo.CompressedLength; - offset += 12; + offset += Constants.OFFSET_CHUNK_INFO; } ushort checksum = PayloadEncoding.Encode( packetInfo.Src + packetInfo.ChunkOffset, packetInfo.ChunkLength, dst + Constants.TCP_HEADER_SIZE + offset, out int l); - *(uint*)(dst + 1) = - ((uint)(l + offset + 1) & Constants.DATA_LENGTH_MASK) | - (packetInfo.CommandOrResponseID << Constants.COMMAND_OR_RESPONSE_ID_SHIFT); + *(ushort*)(dst + 1) = packetInfo.CommandOrResponseID; + *(ushort*)(dst + 3) = (ushort)(l + offset + 1); *(ushort*)(dst + 5) = checksum; *(int*)(dst + Constants.TCP_HEADER_SIZE + offset + l) = Constants.ZERO_BYTE; @@ -94,7 +93,7 @@ internal static bool DeserializeTcp(byte packetHeader, BigDataHandler bigDataHandler, out byte[] payload, ref int length, - out uint requestID, + out ushort requestID, out bool isResponseBitSet) { fixed (byte* ptr = source) @@ -102,13 +101,13 @@ internal static bool DeserializeTcp(byte packetHeader, requestID = 0; int offset = 0; - if ((packetHeader & Constants.REQUEST_BIT_MASK) != 0) + if ((packetHeader & Constants.REQUEST_1_BIT) != 0) { - requestID = *(uint*)ptr; - offset = 4; + requestID = *(ushort*)ptr; + offset = Constants.OFFSET_REQUEST_ID; } - isResponseBitSet = (packetHeader & Constants.RESPONSE_BIT_MASK) != 0; + isResponseBitSet = (packetHeader & Constants.RESPONSE_1_BIT) != 0; int l = 0; CompressionMode compressionMode = @@ -116,7 +115,7 @@ internal static bool DeserializeTcp(byte packetHeader, if (compressionMode != CompressionMode.None) { l = *(int*)(ptr + offset); - offset += 4; + offset += Constants.OFFSET_COMPRESSION_MODE; } int packetId = 0; @@ -124,11 +123,10 @@ internal static bool DeserializeTcp(byte packetHeader, int cl = 0; if ((packetHeader & Constants.IS_CHUNKED_1_BIT) != 0) { - packetId = *(int*)(ptr + offset); - chunkOffset = *(int*)(ptr + offset + 4); - cl = *(int*)(ptr + offset + 8); - - offset += 12; + packetId = *(int*)(ptr + offset); + chunkOffset = *(int*)(ptr + offset + 4); + cl = *(int*)(ptr + offset + 8); + offset += Constants.OFFSET_CHUNK_INFO; } fixed (byte* dst = payload = ByteArrayPool.Rent(length)) diff --git a/src/Exomia.Network/Serialization/Serialization.Udp.cs b/src/Exomia.Network/Serialization/Serialization.Udp.cs index d6c9752..22b9d3a 100644 --- a/src/Exomia.Network/Serialization/Serialization.Udp.cs +++ b/src/Exomia.Network/Serialization/Serialization.Udp.cs @@ -55,14 +55,14 @@ internal static int SerializeUdp(in PacketInfo packetInfo, { *dst |= Constants.REQUEST_1_BIT; *(uint*)(dst + Constants.UDP_HEADER_SIZE) = packetInfo.RequestID; - offset = 4; + offset = Constants.OFFSET_REQUEST_ID; } if (packetInfo.CompressionMode != CompressionMode.None) { *dst |= (byte)packetInfo.CompressionMode; *(int*)(dst + Constants.UDP_HEADER_SIZE + offset) = packetInfo.Length; - offset += 4; + offset += Constants.OFFSET_COMPRESSION_MODE; } if (packetInfo.IsChunked) @@ -71,12 +71,11 @@ internal static int SerializeUdp(in PacketInfo packetInfo, *(int*)(dst + Constants.UDP_HEADER_SIZE + offset) = packetInfo.PacketID; *(int*)(dst + Constants.UDP_HEADER_SIZE + offset + 4) = packetInfo.ChunkOffset; *(int*)(dst + Constants.UDP_HEADER_SIZE + offset + 8) = packetInfo.CompressedLength; - offset += 12; + offset += Constants.OFFSET_CHUNK_INFO; } - *(uint*)(dst + 1) = - ((uint)(packetInfo.ChunkLength + offset) & Constants.DATA_LENGTH_MASK) | - (packetInfo.CommandOrResponseID << Constants.COMMAND_OR_RESPONSE_ID_SHIFT); + *(ushort*)(dst + 1) = packetInfo.CommandOrResponseID; + *(ushort*)(dst + 3) = (ushort)(packetInfo.ChunkLength + offset); Mem.Cpy( dst + Constants.UDP_HEADER_SIZE + offset, packetInfo.Src + packetInfo.ChunkOffset, @@ -98,19 +97,18 @@ internal static bool DeserializeUdp(byte[] buffer, fixed (byte* src = buffer) { byte packetHeader = *src; - uint h2 = *(uint*)(src + 1); - deserializePacketInfo.CommandOrResponseID = h2 >> Constants.COMMAND_OR_RESPONSE_ID_SHIFT; - deserializePacketInfo.Length = (int)(h2 & Constants.DATA_LENGTH_MASK); + deserializePacketInfo.CommandOrResponseID = *(ushort*)(src + 1); + deserializePacketInfo.Length = *(ushort*)(src + 3); deserializePacketInfo.RequestID = 0; - deserializePacketInfo.IsResponseBitSet = (packetHeader & Constants.RESPONSE_BIT_MASK) != 0; + deserializePacketInfo.IsResponseBitSet = (packetHeader & Constants.RESPONSE_1_BIT) != 0; if (bytesTransferred == deserializePacketInfo.Length + Constants.UDP_HEADER_SIZE) { int offset = 0; - if ((packetHeader & Constants.REQUEST_BIT_MASK) != 0) + if ((packetHeader & Constants.REQUEST_1_BIT) != 0) { - deserializePacketInfo.RequestID = *(uint*)(src + Constants.UDP_HEADER_SIZE); - offset = 4; + deserializePacketInfo.RequestID = *(ushort*)(src + Constants.UDP_HEADER_SIZE); + offset = Constants.OFFSET_REQUEST_ID; } int l = 0; @@ -119,7 +117,7 @@ internal static bool DeserializeUdp(byte[] buffer, if (compressionMode != CompressionMode.None) { l = *(int*)(src + Constants.UDP_HEADER_SIZE + offset); - offset += 4; + offset += Constants.OFFSET_COMPRESSION_MODE; } if ((packetHeader & Constants.IS_CHUNKED_1_BIT) != 0) @@ -127,7 +125,8 @@ internal static bool DeserializeUdp(byte[] buffer, int cl = *(int*)(src + Constants.UDP_HEADER_SIZE + offset + 8); byte[]? bdb = bigDataHandler.Receive( keyFunc(*(int*)(src + Constants.UDP_HEADER_SIZE + offset)), - src + Constants.UDP_HEADER_SIZE + offset + 12, deserializePacketInfo.Length - offset - 12, + src + Constants.UDP_HEADER_SIZE + offset + Constants.OFFSET_CHUNK_INFO, + deserializePacketInfo.Length - offset - Constants.OFFSET_CHUNK_INFO, *(int*)(src + Constants.UDP_HEADER_SIZE + offset + 4), cl); deserializePacketInfo.Length = cl; diff --git a/src/Exomia.Network/ServerBase.Send.cs b/src/Exomia.Network/ServerBase.Send.cs index 8be0def..a53252d 100644 --- a/src/Exomia.Network/ServerBase.Send.cs +++ b/src/Exomia.Network/ServerBase.Send.cs @@ -26,7 +26,7 @@ public abstract partial class ServerBase { /// public SendError SendTo(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -37,7 +37,7 @@ public SendError SendTo(TServerClient client, /// public SendError SendTo(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, bool isResponse = false) { @@ -46,7 +46,7 @@ public SendError SendTo(TServerClient client, /// public SendError SendTo(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, bool isResponse = false) { @@ -56,7 +56,7 @@ public SendError SendTo(TServerClient client, /// public SendError SendTo(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in T1 data, bool isResponse = false) where T1 : unmanaged @@ -67,7 +67,7 @@ public SendError SendTo(TServerClient client, /// public async Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -75,10 +75,10 @@ public async Task> SendToR(TServerClient TimeSpan timeout, bool isResponse = false) { - TaskCompletionSource<(uint requestID, Packet packet)> tcs = - new TaskCompletionSource<(uint, Packet)>(TaskCreationOptions.None); + TaskCompletionSource<(ushort requestID, Packet packet)> tcs = + new TaskCompletionSource<(ushort, Packet)>(TaskCreationOptions.None); using CancellationTokenSource cts = new CancellationTokenSource(timeout); - uint requestID; + ushort requestID; bool lockTaken = false; try { @@ -109,7 +109,7 @@ public async Task> SendToR(TServerClient SendError sendError = SendTo(client.Arg0, commandOrResponseID, data, offset, length, requestID, isResponse); if (sendError == SendError.None) { - (uint rID, Packet packet) = await tcs.Task; + (ushort rID, Packet packet) = await tcs.Task; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (packet.Buffer != null) @@ -139,7 +139,7 @@ public async Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, bool isResponse = false) where TResult : unmanaged @@ -151,7 +151,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -165,7 +165,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -178,7 +178,7 @@ public Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, bool isResponse = false) @@ -189,7 +189,7 @@ public Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, @@ -203,7 +203,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, TimeSpan timeout, bool isResponse = false) @@ -215,7 +215,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -226,7 +226,7 @@ public Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, bool isResponse = false) where TResult : unmanaged @@ -239,7 +239,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, bool isResponse = false) @@ -250,7 +250,7 @@ public Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, TimeSpan timeout, bool isResponse = false) @@ -263,7 +263,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, ISerializable serializable, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -275,7 +275,7 @@ public Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in TValue data, bool isResponse = false) where TValue : unmanaged @@ -289,7 +289,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in TValue data, DeserializePacketHandler deserialize, bool isResponse = false) @@ -301,7 +301,7 @@ public Task> SendToR(TServerClient /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in TValue data, TimeSpan timeout, bool isResponse = false) @@ -315,7 +315,7 @@ public Task> SendToR(TServerClient client, /// public Task> SendToR(TServerClient client, - uint commandOrResponseID, + ushort commandOrResponseID, in TValue data, DeserializePacketHandler deserialize, TimeSpan timeout, @@ -326,7 +326,7 @@ public Task> SendToR(TServerClient client, } /// - public void SendToAll(uint commandOrResponseID, byte[] data, int offset, int length) + public void SendToAll(ushort commandOrResponseID, byte[] data, int offset, int length) { Dictionary clients; bool lockTaken = false; @@ -350,13 +350,13 @@ public void SendToAll(uint commandOrResponseID, byte[] data, int offset, int len } /// - public void SendToAll(uint commandOrResponseID, byte[] data) + public void SendToAll(ushort commandOrResponseID, byte[] data) { SendToAll(commandOrResponseID, data, 0, data.Length); } /// - public void SendToAll(uint commandOrResponseID, in T1 data) + public void SendToAll(ushort commandOrResponseID, in T1 data) where T1 : unmanaged { byte[] buffer = data.ToBytesUnsafe2(out int length); @@ -364,7 +364,7 @@ public void SendToAll(uint commandOrResponseID, in T1 data) } /// - public void SendToAll(uint commandOrResponseID, ISerializable serializable) + public void SendToAll(ushort commandOrResponseID, ISerializable serializable) { byte[] buffer = serializable.Serialize(out int length); SendToAll(commandOrResponseID, buffer, 0, length); @@ -386,11 +386,11 @@ private static TResult DeserializeResponse(in Packet packet) } private unsafe SendError SendTo(T arg0, - uint commandOrResponseID, + ushort commandOrResponseID, byte[] data, int offset, int length, - uint requestID = 0, + ushort requestID = 0, bool isResponse = false) { if (_listener == null || (_state & SEND_FLAG) != SEND_FLAG) { return SendError.Invalid; } diff --git a/src/Exomia.Network/ServerBase.cs b/src/Exomia.Network/ServerBase.cs index bafbbbe..f1f9f07 100644 --- a/src/Exomia.Network/ServerBase.cs +++ b/src/Exomia.Network/ServerBase.cs @@ -68,7 +68,7 @@ public event ClientCommandDataReceivedHandler ClientDataReceived private protected Socket? _listener; private protected int _port; - private uint _requestID; + private ushort _requestID; private protected byte _state; /// @@ -77,15 +77,18 @@ public event ClientCommandDataReceivedHandler ClientDataReceived protected CompressionMode _compressionMode = CompressionMode.Lz4; private protected EncryptionMode _encryptionMode = EncryptionMode.None; - private readonly Dictionary> _dataReceivedCallbacks; - private readonly Event> _clientDataReceived; - private readonly Dictionary> _taskCompletionSources; - private readonly byte _listenerCount; - private SpinLock _clientsLock; - private SpinLock _dataReceivedCallbacksLock; - private SpinLock _lockTaskCompletionSources; - private bool _isRunning; - private int _packetID; + private readonly Dictionary> _dataReceivedCallbacks; + private readonly Event> _clientDataReceived; + + private readonly Dictionary> + _taskCompletionSources; + + private readonly byte _listenerCount; + private SpinLock _clientsLock; + private SpinLock _dataReceivedCallbacksLock; + private SpinLock _lockTaskCompletionSources; + private bool _isRunning; + private int _packetID; /// /// Gets the port. @@ -217,9 +220,9 @@ public bool NoDelay private protected ServerBase(byte listenerCount = 1) { _listenerCount = listenerCount; - _dataReceivedCallbacks = new Dictionary>(INITIAL_QUEUE_SIZE); + _dataReceivedCallbacks = new Dictionary>(INITIAL_QUEUE_SIZE); _taskCompletionSources = - new Dictionary>( + new Dictionary>( INITIAL_TASK_COMPLETION_QUEUE_SIZE); _clients = new Dictionary(INITIAL_CLIENT_QUEUE_SIZE); @@ -301,13 +304,13 @@ public bool Run(int port, Action>? overwriteConfigu private protected void DeserializeData(T arg0, in DeserializePacketInfo deserializePacketInfo) { - uint commandOrResponseID = deserializePacketInfo.CommandOrResponseID; - uint requestID = deserializePacketInfo.RequestID; + ushort commandOrResponseID = deserializePacketInfo.CommandOrResponseID; + ushort requestID = deserializePacketInfo.RequestID; if (deserializePacketInfo.IsResponseBitSet) { - TaskCompletionSource<(uint, Packet)>? cs; - bool lockTaken = false; + TaskCompletionSource<(ushort, Packet)>? cs; + bool lockTaken = false; try { _lockTaskCompletionSources.Enter(ref lockTaken); @@ -486,14 +489,24 @@ private void InvokeClientConnected(T arg0) #region Add & Remove + /// + /// add a command deserializer. + /// + /// Identifier for the command. + /// The deserialize handler. + public void AddCommand(ushort commandID, DeserializePacketHandler deserialize) + { + AddCommand(new[] { commandID }, deserialize); + } + /// /// add commands deserializers. /// + /// The command ids. /// The deserialize handler. - /// A variable-length parameters list containing command ids. /// Thrown when one or more required arguments are null. /// Thrown when one or more arguments are outside the required range. - public void AddCommand(DeserializePacketHandler deserialize, params uint[] commandIDs) + public void AddCommand(ushort[] commandIDs, DeserializePacketHandler deserialize) { if (commandIDs.Length <= 0) { throw new ArgumentNullException(nameof(commandIDs)); } if (deserialize == null) { throw new ArgumentNullException(nameof(deserialize)); } @@ -503,7 +516,7 @@ public void AddCommand(DeserializePacketHandler deserialize, params uin { _dataReceivedCallbacksLock.Enter(ref lockTaken); - foreach (uint commandID in commandIDs) + foreach (ushort commandID in commandIDs) { if (commandID > Constants.USER_COMMAND_LIMIT) { @@ -533,7 +546,7 @@ public void AddCommand(DeserializePacketHandler deserialize, params uin /// /// Thrown when one or more required arguments are null. /// Thrown when one or more arguments are outside the required range. - public bool RemoveCommands(params uint[] commandIDs) + public bool RemoveCommands(params ushort[] commandIDs) { if (commandIDs.Length <= 0) { throw new ArgumentNullException(nameof(commandIDs)); } bool removed = false; @@ -541,7 +554,7 @@ public bool RemoveCommands(params uint[] commandIDs) try { _dataReceivedCallbacksLock.Enter(ref lockTaken); - foreach (uint commandID in commandIDs) + foreach (ushort commandID in commandIDs) { if (commandID > Constants.USER_COMMAND_LIMIT) { @@ -566,7 +579,7 @@ public bool RemoveCommands(params uint[] commandIDs) /// Thrown when one or more arguments are outside the required range. /// Thrown when one or more required arguments are null. /// Thrown when an exception error condition occurs. - public void AddDataReceivedCallback(uint commandID, ClientDataReceivedHandler callback) + public void AddDataReceivedCallback(ushort commandID, ClientDataReceivedHandler callback) { if (commandID > Constants.USER_COMMAND_LIMIT) { @@ -601,7 +614,7 @@ public void AddDataReceivedCallback(uint commandID, ClientDataReceivedHandler ClientDataReceivedHandler{Socket|Endpoint} /// Thrown when one or more arguments are outside the required range. /// Thrown when one or more required arguments are null. - public void RemoveDataReceivedCallback(uint commandID, ClientDataReceivedHandler callback) + public void RemoveDataReceivedCallback(ushort commandID, ClientDataReceivedHandler callback) { if (commandID > Constants.USER_COMMAND_LIMIT) { diff --git a/src/Exomia.Network/TCP/TcpClientBase.cs b/src/Exomia.Network/TCP/TcpClientBase.cs index 29fe515..80c90ef 100644 --- a/src/Exomia.Network/TCP/TcpClientBase.cs +++ b/src/Exomia.Network/TCP/TcpClientBase.cs @@ -116,7 +116,7 @@ private protected unsafe void Receive(byte[] buffer, _circularBuffer.Read(ptr, deserializePacketInfo.Length, Constants.TCP_HEADER_SIZE); if (size < bytesTransferred) { - _circularBuffer.Write(buffer, size, bytesTransferred - size); + size += _circularBuffer.Write(buffer, size, bytesTransferred - size); } } diff --git a/src/Exomia.Network/TCP/TcpClientEap.cs b/src/Exomia.Network/TCP/TcpClientEap.cs index c76362a..168d29b 100644 --- a/src/Exomia.Network/TCP/TcpClientEap.cs +++ b/src/Exomia.Network/TCP/TcpClientEap.cs @@ -10,6 +10,7 @@ using System; using System.Net.Sockets; +using System.Threading.Tasks; namespace Exomia.Network.TCP { @@ -77,7 +78,7 @@ private protected override void ReceiveAsync() { if (!_clientSocket!.ReceiveAsync(_receiveEventArgs)) { - ReceiveAsyncCompleted(_receiveEventArgs.AcceptSocket, _receiveEventArgs); + Task.Run(() => ReceiveAsyncCompleted(_receiveEventArgs.AcceptSocket, _receiveEventArgs)); } } catch (ObjectDisposedException) { Disconnect(DisconnectReason.Aborted); } diff --git a/src/Exomia.Network/TCP/TcpServerApmBase.cs b/src/Exomia.Network/TCP/TcpServerApmBase.cs index 7bb162c..7ad13c4 100644 --- a/src/Exomia.Network/TCP/TcpServerApmBase.cs +++ b/src/Exomia.Network/TCP/TcpServerApmBase.cs @@ -54,14 +54,12 @@ private void AcceptCallback(IAsyncResult ar) try { Socket socket = _listener!.EndAccept(ar); -#pragma warning disable IDE0068 // Use recommended dispose pattern ServerClientStateObjectApm state = new ServerClientStateObjectApm( new byte[_payloadSize + Constants.TCP_HEADER_OFFSET], new CircularBuffer((_payloadSize + Constants.TCP_HEADER_OFFSET) * 2), new BigDataHandler.Default(), socket, new byte[_payloadSize + Constants.TCP_HEADER_OFFSET]); -#pragma warning restore IDE0068 // Use recommended dispose pattern ReceiveAsync(state); } catch (ObjectDisposedException) diff --git a/src/Exomia.Network/TCP/TcpServerBase.cs b/src/Exomia.Network/TCP/TcpServerBase.cs index 146c40f..b4acc5c 100644 --- a/src/Exomia.Network/TCP/TcpServerBase.cs +++ b/src/Exomia.Network/TCP/TcpServerBase.cs @@ -92,8 +92,8 @@ private protected override void OnAfterClientDisconnect(TServerClient client) { try { - client.Arg0?.Shutdown(SocketShutdown.Both); - client.Arg0?.Close(CLOSE_TIMEOUT); + client.Arg0.Shutdown(SocketShutdown.Both); + client.Arg0.Close(CLOSE_TIMEOUT); } catch { diff --git a/src/Exomia.Network/TCP/TcpServerEapBase.cs b/src/Exomia.Network/TCP/TcpServerEapBase.cs index 93e6652..8f255ad 100644 --- a/src/Exomia.Network/TCP/TcpServerEapBase.cs +++ b/src/Exomia.Network/TCP/TcpServerEapBase.cs @@ -10,6 +10,7 @@ using System; using System.Net.Sockets; +using System.Threading.Tasks; using Exomia.Network.Native; namespace Exomia.Network.TCP @@ -26,13 +27,11 @@ public abstract class TcpServerEapBase : TcpServerBase /// Initializes a new instance of the class. /// - /// (Optional) The expected maximum clients. /// (Optional) Size of the expected maximum payload. - protected TcpServerEapBase(ushort expectedMaxClients = 32, - ushort expectedMaxPayloadSize = Constants.TCP_PAYLOAD_SIZE_MAX) + protected TcpServerEapBase(ushort expectedMaxPayloadSize = Constants.TCP_PAYLOAD_SIZE_MAX) : base(expectedMaxPayloadSize) { - _sendEventArgsPool = new SocketAsyncEventArgsPool(expectedMaxClients); + _sendEventArgsPool = new SocketAsyncEventArgsPool(0xFF); } private void ListenAsync(SocketAsyncEventArgs acceptArgs) @@ -97,7 +96,10 @@ private void ReceiveAsync(SocketAsyncEventArgs args) { if (!args.AcceptSocket.ReceiveAsync(args)) { - ReceiveAsyncCompleted(args.AcceptSocket, args); + // ReSharper disable AccessToDisposedClosure + Task.Run(() => ReceiveAsyncCompleted(args.AcceptSocket, args)); + + // ReSharper enable AccessToDisposedClosure } } catch (ObjectDisposedException) diff --git a/src/Exomia.Network/UDP/UdpClientEap.cs b/src/Exomia.Network/UDP/UdpClientEap.cs index 1f324f9..2c522ca 100644 --- a/src/Exomia.Network/UDP/UdpClientEap.cs +++ b/src/Exomia.Network/UDP/UdpClientEap.cs @@ -10,6 +10,7 @@ using System; using System.Net.Sockets; +using System.Threading.Tasks; namespace Exomia.Network.UDP { @@ -72,19 +73,18 @@ private protected override void ReceiveAsync() SocketAsyncEventArgs? receiveEventArgs = _receiveEventArgsPool.Rent(); if (receiveEventArgs == null) { -#pragma warning disable IDE0068 // Use recommended dispose pattern - receiveEventArgs = new SocketAsyncEventArgs(); -#pragma warning restore IDE0068 // Use recommended dispose pattern + receiveEventArgs = new SocketAsyncEventArgs(); receiveEventArgs.Completed += ReceiveAsyncCompleted; receiveEventArgs.SetBuffer( new byte[MaxPayloadSize + Constants.UDP_HEADER_OFFSET], 0, MaxPayloadSize + Constants.UDP_HEADER_OFFSET); } + try { if (!_clientSocket!.ReceiveAsync(receiveEventArgs)) { - ReceiveAsyncCompleted(receiveEventArgs.RemoteEndPoint, receiveEventArgs); + Task.Run(() => ReceiveAsyncCompleted(receiveEventArgs.RemoteEndPoint, receiveEventArgs)); } } catch (ObjectDisposedException) diff --git a/src/Exomia.Network/UDP/UdpServerApmBase.cs b/src/Exomia.Network/UDP/UdpServerApmBase.cs index e17d774..25286ea 100644 --- a/src/Exomia.Network/UDP/UdpServerApmBase.cs +++ b/src/Exomia.Network/UDP/UdpServerApmBase.cs @@ -27,13 +27,11 @@ public abstract class UdpServerApmBase : UdpServerBase /// Initializes a new instance of the class. /// - /// The expected maximum clients. /// (Optional) Size of the expected maximum payload. - protected UdpServerApmBase(ushort expectedMaxClients, - ushort expectedMaxPayloadSize = Constants.UDP_PAYLOAD_SIZE_MAX) + protected UdpServerApmBase(ushort expectedMaxPayloadSize = Constants.UDP_PAYLOAD_SIZE_MAX) : base(expectedMaxPayloadSize) { - _serverClientStateObjectPool = new ObjectPool(expectedMaxClients); + _serverClientStateObjectPool = new ObjectPool(0xFF); } private void SendDataToCallback(IAsyncResult iar) diff --git a/src/Exomia.Network/UDP/UdpServerEapBase.cs b/src/Exomia.Network/UDP/UdpServerEapBase.cs index fbc8bdb..35cd9d2 100644 --- a/src/Exomia.Network/UDP/UdpServerEapBase.cs +++ b/src/Exomia.Network/UDP/UdpServerEapBase.cs @@ -11,6 +11,7 @@ using System; using System.Net; using System.Net.Sockets; +using System.Threading.Tasks; namespace Exomia.Network.UDP { @@ -27,14 +28,12 @@ public abstract class UdpServerEapBase : UdpServerBase /// Initializes a new instance of the class. /// - /// The expected maximum clients. /// (Optional) Size of the expected maximum payload. - protected UdpServerEapBase(ushort expectedMaxClients, - ushort expectedMaxPayloadSize = Constants.UDP_PAYLOAD_SIZE_MAX) + protected UdpServerEapBase(ushort expectedMaxPayloadSize = Constants.UDP_PAYLOAD_SIZE_MAX) : base(expectedMaxPayloadSize) { - _receiveEventArgsPool = new SocketAsyncEventArgsPool((ushort)(expectedMaxClients + 5)); - _sendEventArgsPool = new SocketAsyncEventArgsPool((ushort)(expectedMaxClients + 5)); + _receiveEventArgsPool = new SocketAsyncEventArgsPool(0xFF); + _sendEventArgsPool = new SocketAsyncEventArgsPool(0xFF); } /// @@ -42,8 +41,8 @@ protected override void OnDispose(bool disposing) { if (disposing) { - _receiveEventArgsPool?.Dispose(); - _sendEventArgsPool?.Dispose(); + _receiveEventArgsPool.Dispose(); + _sendEventArgsPool.Dispose(); } } @@ -89,9 +88,7 @@ private protected override void ListenAsync() SocketAsyncEventArgs? receiveEventArgs = _receiveEventArgsPool.Rent(); if (receiveEventArgs == null) { -#pragma warning disable IDE0068 // Use recommended dispose pattern - receiveEventArgs = new SocketAsyncEventArgs(); -#pragma warning restore IDE0068 // Use recommended dispose pattern + receiveEventArgs = new SocketAsyncEventArgs(); receiveEventArgs.Completed += ReceiveFromAsyncCompleted; receiveEventArgs.SetBuffer( new byte[MaxPayloadSize + Constants.UDP_HEADER_OFFSET], @@ -104,7 +101,7 @@ private protected override void ListenAsync() { if (!_listener!.ReceiveFromAsync(receiveEventArgs)) { - ReceiveFromAsyncCompleted(receiveEventArgs.RemoteEndPoint, receiveEventArgs); + Task.Run(() => ReceiveFromAsyncCompleted(receiveEventArgs.RemoteEndPoint, receiveEventArgs)); } } catch diff --git a/tests/L0/Exomia.Network.Tests/Native/CircularBufferTest.cs b/tests/L0/Exomia.Network.Tests/Native/CircularBufferTest.cs index 5fe726b..c779c82 100644 --- a/tests/L0/Exomia.Network.Tests/Native/CircularBufferTest.cs +++ b/tests/L0/Exomia.Network.Tests/Native/CircularBufferTest.cs @@ -653,16 +653,16 @@ public void PeekHeaderTest() byte[] buffer = { 12, 200, 4, 45, 177, 78, 147 }; - Assert.IsFalse(cb.PeekHeader(0, out byte h, out uint c1, out int d, out ushort c2)); + Assert.IsFalse(cb.PeekHeader(0, out byte h, out ushort c1, out int d, out ushort c2)); cb.Write(buffer, 0, buffer.Length); // 7 Assert.IsTrue( - cb.PeekHeader(0, out byte packetHeader, out uint commandID, out int dataLength, out ushort checksum)); + cb.PeekHeader(0, out byte packetHeader, out ushort commandID, out int dataLength, out ushort checksum)); Assert.AreEqual(packetHeader, buffer[0]); - Assert.AreEqual(commandID, (uint)((buffer[4] << 8) | buffer[3])); - Assert.AreEqual(dataLength, (buffer[2] << 8) | buffer[1]); + Assert.AreEqual(commandID, (ushort)((buffer[2] << 8) | buffer[1])); + Assert.AreEqual(dataLength, (buffer[4] << 8) | buffer[3]); Assert.AreEqual(checksum, (ushort)((buffer[6] << 8) | buffer[5])); cb.Write(buffer, 0, buffer.Length); // 14 @@ -671,8 +671,8 @@ public void PeekHeaderTest() Assert.IsTrue(cb.PeekHeader(7, out packetHeader, out commandID, out dataLength, out checksum)); Assert.AreEqual(packetHeader, buffer[0]); - Assert.AreEqual(commandID, (uint)((buffer[4] << 8) | buffer[3])); - Assert.AreEqual(dataLength, (buffer[2] << 8) | buffer[1]); + Assert.AreEqual(commandID, (ushort)((buffer[2] << 8) | buffer[1])); + Assert.AreEqual(dataLength, (buffer[4] << 8) | buffer[3]); Assert.AreEqual(checksum, (ushort)((buffer[6] << 8) | buffer[5])); cb.Skip(7); @@ -682,8 +682,8 @@ public void PeekHeaderTest() Assert.AreEqual(packetHeader, buffer[0]); - Assert.AreEqual(commandID, (uint)((buffer[4] << 8) | buffer[3])); - Assert.AreEqual(dataLength, (buffer[2] << 8) | buffer[1]); + Assert.AreEqual(commandID, (ushort)((buffer[2] << 8) | buffer[1])); + Assert.AreEqual(dataLength, (buffer[4] << 8) | buffer[3]); Assert.AreEqual(checksum, (ushort)((buffer[6] << 8) | buffer[5])); cb.Skip(7); @@ -693,8 +693,8 @@ public void PeekHeaderTest() Assert.AreEqual(packetHeader, buffer[0]); - Assert.AreEqual(commandID, (uint)((buffer[4] << 8) | buffer[3])); - Assert.AreEqual(dataLength, (buffer[2] << 8) | buffer[1]); + Assert.AreEqual(commandID, (ushort)((buffer[2] << 8) | buffer[1])); + Assert.AreEqual(dataLength, (buffer[4] << 8) | buffer[3]); Assert.AreEqual(checksum, (ushort)((buffer[6] << 8) | buffer[5])); }