From 6745861f141a178056948e2c68d81c8160039839 Mon Sep 17 00:00:00 2001 From: Felipe Muniz Date: Tue, 25 Aug 2020 10:37:13 -0300 Subject: [PATCH] refactor in code and docs. --- .../KingNetwork.Benchmarks.Load/RunClients.cs | 9 +- .../Program.cs | 9 +- .../Program.cs | 11 +- .../Interfaces/INetworkListener.cs | 40 +++ .../Interfaces/IPacketHandler.cs | 5 +- src/KingNetwork.Client/KingClient.cs | 34 ++- .../{ => Listeners}/NetworkListener.cs | 40 +-- .../{ => Listeners}/TcpNetworkListener.cs | 19 +- .../{ => Listeners}/UdpNetworkListener.cs | 19 +- .../{ => Listeners}/WSNetworkListener.cs | 33 +- .../NetworkListenerFactory.cs | 19 -- src/KingNetwork.Client/PacketHandler.cs | 13 +- .../{KingBaseClient.cs => Clients/Client.cs} | 41 +-- .../TcpClient.cs} | 36 ++- .../UDPClient.cs} | 24 +- .../WSClient.cs} | 40 +-- src/KingNetwork.Server/Interfaces/IClient.cs | 6 +- .../Interfaces/INetworkListener.cs | 25 ++ .../Interfaces/IPacketHandler.cs | 6 +- src/KingNetwork.Server/KingServer.cs | 52 ++-- .../{ => Listeners}/NetworkListener.cs | 38 ++- .../{ => Listeners}/TcpNetworkListener.cs | 6 +- .../{ => Listeners}/UdpNetworkListener.cs | 11 +- .../WebSocketNetworkListener.cs | 5 +- .../NetworkListenerFactory.cs | 22 -- src/KingNetwork.Server/PacketHandler.cs | 14 +- .../Interfaces/IKingBufferReader.cs | 235 ++++++++++++++ .../{ => Interfaces}/IKingBufferWriter.cs | 31 +- src/KingNetwork.Shared/KingBufferReader.cs | 286 ++++++------------ src/KingNetwork.Shared/KingBufferWriter.cs | 189 +++--------- .../KingNetwork.Shared.csproj | 2 +- 31 files changed, 689 insertions(+), 631 deletions(-) create mode 100644 src/KingNetwork.Client/Interfaces/INetworkListener.cs rename src/KingNetwork.Client/{ => Listeners}/NetworkListener.cs (72%) rename src/KingNetwork.Client/{ => Listeners}/TcpNetworkListener.cs (82%) rename src/KingNetwork.Client/{ => Listeners}/UdpNetworkListener.cs (84%) rename src/KingNetwork.Client/{ => Listeners}/WSNetworkListener.cs (77%) delete mode 100644 src/KingNetwork.Client/NetworkListenerFactory.cs rename src/KingNetwork.Server/{KingBaseClient.cs => Clients/Client.cs} (56%) rename src/KingNetwork.Server/{KingTcpClient.cs => Clients/TcpClient.cs} (79%) rename src/KingNetwork.Server/{KingUdpClient.cs => Clients/UDPClient.cs} (78%) rename src/KingNetwork.Server/{KingWebSocketClient.cs => Clients/WSClient.cs} (79%) create mode 100644 src/KingNetwork.Server/Interfaces/INetworkListener.cs rename src/KingNetwork.Server/{ => Listeners}/NetworkListener.cs (77%) rename src/KingNetwork.Server/{ => Listeners}/TcpNetworkListener.cs (90%) rename src/KingNetwork.Server/{ => Listeners}/UdpNetworkListener.cs (91%) rename src/KingNetwork.Server/{ => Listeners}/WebSocketNetworkListener.cs (92%) delete mode 100644 src/KingNetwork.Server/NetworkListenerFactory.cs create mode 100644 src/KingNetwork.Shared/Interfaces/IKingBufferReader.cs rename src/KingNetwork.Shared/{ => Interfaces}/IKingBufferWriter.cs (92%) diff --git a/examples/Benchmarks/KingNetwork.Benchmarks.Load/RunClients.cs b/examples/Benchmarks/KingNetwork.Benchmarks.Load/RunClients.cs index a3ea30a..dd3a79e 100644 --- a/examples/Benchmarks/KingNetwork.Benchmarks.Load/RunClients.cs +++ b/examples/Benchmarks/KingNetwork.Benchmarks.Load/RunClients.cs @@ -1,5 +1,6 @@ using KingNetwork.Client; using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Collections.Generic; using System.Diagnostics; @@ -158,14 +159,14 @@ public static void StartClients(string ip, int clientConnections) /// /// Method responsible for execute the callback of message received from server in client. /// - /// The king buffer from received message. - private static void OnMessageReceived(KingBufferReader kingBuffer) + /// The king buffer reader from received message. + private static void OnMessageReceived(IKingBufferReader reader) { try { _messagesReceived++; - _dataReceived += kingBuffer.Length; - _bufferLength = kingBuffer.Length; + _dataReceived += reader.Length; + _bufferLength = reader.Length; //if (_networkListenerType == NetworkListenerType.WS) //{ diff --git a/examples/Console/SimpleExample/KingNetwork.SimpleExample.Client/Program.cs b/examples/Console/SimpleExample/KingNetwork.SimpleExample.Client/Program.cs index 0a72b64..47447ba 100644 --- a/examples/Console/SimpleExample/KingNetwork.SimpleExample.Client/Program.cs +++ b/examples/Console/SimpleExample/KingNetwork.SimpleExample.Client/Program.cs @@ -1,5 +1,6 @@ using KingNetwork.Client; using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using KingNetwork.SimpleExample.Shared; using System; using System.Threading; @@ -53,15 +54,15 @@ static void Main(string[] args) /// /// Method responsible for execute the callback of message received from server in client. /// - /// The king buffer from received message. - private static void OnMessageReceived(KingBufferReader kingBuffer) + /// The king buffer reader from received message. + private static void OnMessageReceived(IKingBufferReader reader) { try { if (_networkListenerType == NetworkListenerType.WSText) - Console.WriteLine($"OnMessageReceived: {kingBuffer.ReadString()}"); + Console.WriteLine($"OnMessageReceived: {reader.ReadString()}"); else - switch (kingBuffer.ReadMessagePacket()) + switch (reader.ReadMessagePacket()) { case MyPackets.PacketOne: Console.WriteLine("OnMessageReceived for PacketOne"); diff --git a/examples/Console/SimpleExample/KingNetwork.SimpleExample.Server/Program.cs b/examples/Console/SimpleExample/KingNetwork.SimpleExample.Server/Program.cs index 3593b0c..055182f 100644 --- a/examples/Console/SimpleExample/KingNetwork.SimpleExample.Server/Program.cs +++ b/examples/Console/SimpleExample/KingNetwork.SimpleExample.Server/Program.cs @@ -3,6 +3,7 @@ using KingNetwork.Server.Interfaces; using KingNetwork.Shared; using KingNetwork.SimpleExample.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.SimpleExample.Server { @@ -39,8 +40,8 @@ static void Main(string[] args) /// Method responsible for execute the callback of message received from client in server. /// /// The client instance. - /// The king buffer from received message. - private static void OnMessageReceived(IClient client, KingBufferReader kingBuffer) + /// The king buffer reader from received message. + private static void OnMessageReceived(IClient client, IKingBufferReader reader) { try { @@ -48,7 +49,7 @@ private static void OnMessageReceived(IClient client, KingBufferReader kingBuffe { Console.WriteLine($"OnMessageReceived from {client.Id}"); - string text = kingBuffer.ReadString(); + string text = reader.ReadString(); Console.WriteLine($"Message: {text}"); var writer = KingBufferWriter.Create(); @@ -59,11 +60,11 @@ private static void OnMessageReceived(IClient client, KingBufferReader kingBuffe } else { - switch (kingBuffer.ReadMessagePacket()) + switch (reader.ReadMessagePacket()) { case MyPackets.PacketOne: Console.WriteLine($"OnMessageReceived PacketOne from {client.Id}"); - Console.WriteLine($"Message: {kingBuffer.ReadString()}"); + Console.WriteLine($"Message: {reader.ReadString()}"); var writer = KingBufferWriter.Create(); diff --git a/src/KingNetwork.Client/Interfaces/INetworkListener.cs b/src/KingNetwork.Client/Interfaces/INetworkListener.cs new file mode 100644 index 0000000..7806ab5 --- /dev/null +++ b/src/KingNetwork.Client/Interfaces/INetworkListener.cs @@ -0,0 +1,40 @@ +using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; + +namespace KingNetwork.Client.Interfaces +{ + /// + /// This class is responsible for representation of network listener. + /// + internal interface INetworkListener + { + /// + /// Method responsible for start the client network tcp listener. + /// + /// The ip address of server. + /// The port of server. + /// The max length of message buffer. + void StartClient(string ip, int port, ushort maxMessageBuffer); + + /// + /// Method responsible for send message to connected server. + /// + /// The king buffer writer of received message. + void SendMessage(IKingBufferWriter writer); + + /// + /// This method is responsible for call the dispose implementation method. + /// + void Dispose(); + + /// + /// This method is responsible for verify if listener has connected. + /// + bool Connected(); + + /// + /// Method responsible for stop the tcp network listener. + /// + void Stop(); + } +} diff --git a/src/KingNetwork.Client/Interfaces/IPacketHandler.cs b/src/KingNetwork.Client/Interfaces/IPacketHandler.cs index 351d10b..501a70a 100644 --- a/src/KingNetwork.Client/Interfaces/IPacketHandler.cs +++ b/src/KingNetwork.Client/Interfaces/IPacketHandler.cs @@ -1,4 +1,5 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Client.Interfaces { @@ -10,7 +11,7 @@ internal interface IPacketHandler /// /// This method is responsible for receive the message from client packet handler. /// - /// The king buffer of received message. - void HandleMessageData(KingBufferReader kingBuffer); + /// The king buffer reader of received message. + void HandleMessageData(IKingBufferReader reader); } } diff --git a/src/KingNetwork.Client/KingClient.cs b/src/KingNetwork.Client/KingClient.cs index 8e54c0d..7f97161 100644 --- a/src/KingNetwork.Client/KingClient.cs +++ b/src/KingNetwork.Client/KingClient.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Threading; -using KingNetwork.client; +using KingNetwork.Client.Interfaces; +using KingNetwork.Client.Listeners; using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Client { @@ -21,7 +23,7 @@ public class KingClient /// /// The network listener instance. /// - private NetworkListener _networkListener; + private INetworkListener _networkListener; /// /// The thread for start the network listener. @@ -49,8 +51,8 @@ public class KingClient /// /// The client packet handler delegate. /// - /// The king buffer of received message. - public delegate void ClientPacketHandler(KingBufferReader kingBuffer); + /// The king buffer reader of received message. + public delegate void ClientPacketHandler(IKingBufferReader reader); #endregion @@ -128,7 +130,13 @@ public void Connect(string ip, ushort port = 7171, NetworkListenerType listenerT { _clientThread = new Thread(() => { - _networkListener = NetworkListenerFactory.CreateForType(listenerType, OnMessageReceived, OnClientDisconnected); + if (listenerType == NetworkListenerType.TCP) + _networkListener = new TcpNetworkListener(OnMessageReceived, OnClientDisconnected); + else if (listenerType == NetworkListenerType.UDP) + _networkListener = new UdpNetworkListener(OnMessageReceived, OnClientDisconnected); + else if (listenerType == NetworkListenerType.WSBinary || listenerType == NetworkListenerType.WSText) + _networkListener = new WSNetworkListener(listenerType, OnMessageReceived, OnClientDisconnected); + _networkListener.StartClient(ip, port, maxMessageBuffer); }); @@ -159,12 +167,12 @@ public void Disconnect() /// /// Method responsible for send message to connected server. /// - /// The king buffer to send message. - public void SendMessage(KingBufferWriter kingBuffer) + /// The king buffer writer to send message. + public void SendMessage(IKingBufferWriter writer) { try { - _networkListener.SendMessage(kingBuffer); + _networkListener.SendMessage(writer); } catch (Exception ex) { @@ -179,15 +187,15 @@ public void SendMessage(KingBufferWriter kingBuffer) /// /// Method responsible for execute the callback of message received from client in server. /// - /// The king buffer of received message. - private void OnMessageReceived(KingBufferReader kingBuffer) + /// The king buffer reader of received message. + private void OnMessageReceived(IKingBufferReader reader) { try { - if (kingBuffer.Length > 0 && _clientPacketHandlers.Count > 0 && _clientPacketHandlers.TryGetValue(kingBuffer.ReadByte(), out var clientPacketHandler)) - clientPacketHandler(kingBuffer); + if (reader.Length > 0 && _clientPacketHandlers.Count > 0 && _clientPacketHandlers.TryGetValue(reader.ReadByte(), out var clientPacketHandler)) + clientPacketHandler(reader); else - MessageReceivedHandler(kingBuffer); + MessageReceivedHandler(reader); } catch (Exception ex) { diff --git a/src/KingNetwork.Client/NetworkListener.cs b/src/KingNetwork.Client/Listeners/NetworkListener.cs similarity index 72% rename from src/KingNetwork.Client/NetworkListener.cs rename to src/KingNetwork.Client/Listeners/NetworkListener.cs index 527913e..4f0d9c2 100644 --- a/src/KingNetwork.Client/NetworkListener.cs +++ b/src/KingNetwork.Client/Listeners/NetworkListener.cs @@ -1,14 +1,16 @@ -using KingNetwork.Shared; +using KingNetwork.Client.Interfaces; +using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Net; using System.Net.Sockets; -namespace KingNetwork.Client +namespace KingNetwork.Client.Listeners { /// /// This class is responsible for representation of abstract network listener. /// - public abstract class NetworkListener : IDisposable + public abstract class NetworkListener : INetworkListener, IDisposable { #region private members @@ -45,7 +47,7 @@ public abstract class NetworkListener : IDisposable /// /// The value for remote end point. /// - public EndPoint _remoteEndPoint; + protected EndPoint _remoteEndPoint; #endregion @@ -54,8 +56,8 @@ public abstract class NetworkListener : IDisposable /// /// The delegate of message received handler from server connection. /// - /// The king buffer of received message. - public delegate void MessageReceivedHandler(KingBufferReader kingBuffer); + /// The king buffer reader of received message. + public delegate void MessageReceivedHandler(IKingBufferReader reader); /// /// The delegate of client disconnected handler connection. @@ -88,33 +90,19 @@ public NetworkListener(MessageReceivedHandler messageReceivedHandler, ClientDisc #region public methods implementation - /// - /// Method responsible for start the client network tcp listener. - /// - /// The ip address of server. - /// The port of server. - /// The max length of message buffer. + /// public virtual void StartClient(string ip, int port, ushort maxMessageBuffer) { } - /// - /// Method responsible for send message to connected server. - /// - /// The king buffer of received message. - public virtual void SendMessage(KingBufferWriter kingBuffer) { } + /// + public virtual void SendMessage(IKingBufferWriter writer) { } - /// - /// This method is responsible for call the dispose implementation method. - /// + /// public void Dispose() => Dispose(true); - /// - /// This method is responsible for verify if listener has connected. - /// + /// public bool Connected() => _listener.Connected; - /// - /// Method responsible for stop the tcp network listener. - /// + /// public void Stop() { try diff --git a/src/KingNetwork.Client/TcpNetworkListener.cs b/src/KingNetwork.Client/Listeners/TcpNetworkListener.cs similarity index 82% rename from src/KingNetwork.Client/TcpNetworkListener.cs rename to src/KingNetwork.Client/Listeners/TcpNetworkListener.cs index 55d5482..bf31d78 100644 --- a/src/KingNetwork.Client/TcpNetworkListener.cs +++ b/src/KingNetwork.Client/Listeners/TcpNetworkListener.cs @@ -1,9 +1,10 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Net; using System.Net.Sockets; -namespace KingNetwork.Client +namespace KingNetwork.Client.Listeners { /// /// This class is responsible for managing the network tcp listener. @@ -24,12 +25,7 @@ public TcpNetworkListener(MessageReceivedHandler messageReceivedHandler, ClientD #region public methods implementation - /// - /// Method responsible for start the client network tcp listener. - /// - /// The ip address of server. - /// The port of server. - /// The max length of message buffer. + /// public override void StartClient(string ip, int port, ushort maxMessageBuffer) { try @@ -53,15 +49,12 @@ public override void StartClient(string ip, int port, ushort maxMessageBuffer) } } - /// - /// Method responsible for send message to connected server. - /// - /// The king buffer of received message. - public override void SendMessage(KingBufferWriter kingBuffer) + /// + public override void SendMessage(IKingBufferWriter writer) { try { - _stream.BeginWrite(kingBuffer.BufferData, 0, kingBuffer.Length, null, null); + _stream.BeginWrite(writer.BufferData, 0, writer.Length, null, null); } catch (Exception ex) { diff --git a/src/KingNetwork.Client/UdpNetworkListener.cs b/src/KingNetwork.Client/Listeners/UdpNetworkListener.cs similarity index 84% rename from src/KingNetwork.Client/UdpNetworkListener.cs rename to src/KingNetwork.Client/Listeners/UdpNetworkListener.cs index dce1004..fcab913 100644 --- a/src/KingNetwork.Client/UdpNetworkListener.cs +++ b/src/KingNetwork.Client/Listeners/UdpNetworkListener.cs @@ -1,9 +1,10 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Net; using System.Net.Sockets; -namespace KingNetwork.Client +namespace KingNetwork.Client.Listeners { /// /// This class is responsible for managing the network udp listener. @@ -24,12 +25,7 @@ public UdpNetworkListener(MessageReceivedHandler messageReceivedHandler, ClientD #region public methods implementation - /// - /// Method responsible for start the client network udp listener. - /// - /// The ip address of server. - /// The port of server. - /// The max length of message buffer. + /// public override void StartClient(string ip, int port, ushort maxMessageBuffer) { try @@ -69,15 +65,12 @@ public override void StartClient(string ip, int port, ushort maxMessageBuffer) } } - /// - /// Method responsible for send message to connected server. - /// - /// The king buffer of received message. - public override void SendMessage(KingBufferWriter kingBuffer) + /// + public override void SendMessage(IKingBufferWriter writer) { try { - _listener.SendTo(kingBuffer.BufferData, _remoteEndPoint); + _listener.SendTo(writer.BufferData, _remoteEndPoint); } catch (Exception ex) { diff --git a/src/KingNetwork.Client/WSNetworkListener.cs b/src/KingNetwork.Client/Listeners/WSNetworkListener.cs similarity index 77% rename from src/KingNetwork.Client/WSNetworkListener.cs rename to src/KingNetwork.Client/Listeners/WSNetworkListener.cs index 645d90c..ea210d4 100644 --- a/src/KingNetwork.Client/WSNetworkListener.cs +++ b/src/KingNetwork.Client/Listeners/WSNetworkListener.cs @@ -1,10 +1,11 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Linq; using System.Net.WebSockets; using System.Threading; -namespace KingNetwork.Client +namespace KingNetwork.Client.Listeners { /// /// This class is responsible for managing the network websocket listener. @@ -53,12 +54,7 @@ public WSNetworkListener(NetworkListenerType listenerType, MessageReceivedHandle #region public methods implementation - /// - /// Method responsible for start the client network websocket listener. - /// - /// The ip address of server. - /// The port of server. - /// The max length of message buffer. + /// public override void StartClient(string ip, int port, ushort maxMessageBuffer) { try @@ -75,11 +71,8 @@ public override void StartClient(string ip, int port, ushort maxMessageBuffer) } } - /// - /// Method responsible for send message to connected server. - /// - /// The king buffer of received message. - public override void SendMessage(KingBufferWriter kingBuffer) + /// + public override void SendMessage(IKingBufferWriter writer) { try { @@ -87,12 +80,12 @@ public override void SendMessage(KingBufferWriter kingBuffer) { if (_listenerType == NetworkListenerType.WSText) { - var data = new ArraySegment(kingBuffer.BufferData, 4, kingBuffer.BufferData.Length - 4); + var data = new ArraySegment(writer.BufferData, 4, writer.BufferData.Length - 4); _clientWebSocket.SendAsync(data, WebSocketMessageType.Text, true, CancellationToken.None); } else if (_listenerType == NetworkListenerType.WSBinary) { - var data = new ArraySegment(kingBuffer.BufferData); + var data = new ArraySegment(writer.BufferData); _clientWebSocket.SendAsync(data, WebSocketMessageType.Binary, true, CancellationToken.None); } } @@ -126,17 +119,17 @@ public async void StartConnection(Uri uri) { var data = _buff.Take(ret.Count).ToArray(); - var writter = KingBufferWriter.Create(); - writter.Write(data); + var writer = KingBufferWriter.Create(); + writer.Write(data); - var buffer = KingBufferReader.Create(writter.BufferData, 0, writter.Length); + var reader = KingBufferReader.Create(writer.BufferData, 0, writer.Length); - _messageReceivedHandler(buffer); + _messageReceivedHandler(reader); } else if (ret.MessageType == WebSocketMessageType.Binary) { - var kingBuffer = KingBufferReader.Create(_buff.Take(ret.Count).ToArray(), 0, ret.Count); - _messageReceivedHandler(kingBuffer); + var reader = KingBufferReader.Create(_buff.Take(ret.Count).ToArray(), 0, ret.Count); + _messageReceivedHandler(reader); } } } diff --git a/src/KingNetwork.Client/NetworkListenerFactory.cs b/src/KingNetwork.Client/NetworkListenerFactory.cs deleted file mode 100644 index 7253eb6..0000000 --- a/src/KingNetwork.Client/NetworkListenerFactory.cs +++ /dev/null @@ -1,19 +0,0 @@ -using KingNetwork.Client; -using KingNetwork.Shared; -using static KingNetwork.Client.NetworkListener; - -namespace KingNetwork.client -{ - public static class NetworkListenerFactory - { - public static NetworkListener CreateForType(NetworkListenerType listenerType, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler) - { - if (listenerType == NetworkListenerType.TCP) - return new TcpNetworkListener(messageReceivedHandler, clientDisconnectedHandler); - else if (listenerType == NetworkListenerType.WSBinary || listenerType == NetworkListenerType.WSText) - return new WSNetworkListener(listenerType, messageReceivedHandler, clientDisconnectedHandler); - - return new UdpNetworkListener(messageReceivedHandler, clientDisconnectedHandler); - } - } -} diff --git a/src/KingNetwork.Client/PacketHandler.cs b/src/KingNetwork.Client/PacketHandler.cs index 5154f21..bce18ee 100644 --- a/src/KingNetwork.Client/PacketHandler.cs +++ b/src/KingNetwork.Client/PacketHandler.cs @@ -1,17 +1,12 @@ using KingNetwork.Client.Interfaces; -using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Client { - /// - /// This class is responsible for representation of abstract client packet handler. - /// + /// public abstract class PacketHandler : IPacketHandler { - /// - /// This method is responsible for receive the message from client packet handler. - /// - /// The king buffer of received message. - public abstract void HandleMessageData(KingBufferReader kingBuffer); + /// + public abstract void HandleMessageData(IKingBufferReader reader); } } diff --git a/src/KingNetwork.Server/KingBaseClient.cs b/src/KingNetwork.Server/Clients/Client.cs similarity index 56% rename from src/KingNetwork.Server/KingBaseClient.cs rename to src/KingNetwork.Server/Clients/Client.cs index bbff871..c59f2e9 100644 --- a/src/KingNetwork.Server/KingBaseClient.cs +++ b/src/KingNetwork.Server/Clients/Client.cs @@ -1,5 +1,6 @@ using KingNetwork.Server.Interfaces; using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System.Net.Sockets; namespace KingNetwork.Server @@ -7,25 +8,10 @@ namespace KingNetwork.Server /// /// This class is responsible for represents the client connection. /// - public abstract class KingBaseClient : IClient + public abstract class Client : IClient { #region private members - /// - /// The tcp client instance from client. - /// - protected Socket _socketClient; - - /// - /// The buffer of client connection. - /// - protected byte[] _buffer; - - /// - /// The stream of tcp client. - /// - protected NetworkStream _stream; - /// /// The callback of message received handler implementation. /// @@ -40,19 +26,13 @@ public abstract class KingBaseClient : IClient #region properties - /// - /// The identifier number of client. - /// + /// public ushort Id { get; set; } - /// - /// The ip address of connected client. - /// + /// public string IpAddress { get; } - /// - /// The flag of client connection. - /// + /// public abstract bool IsConnected { get; } #endregion @@ -63,8 +43,8 @@ public abstract class KingBaseClient : IClient /// The delegate of message received handler from client connection. /// /// The client instance. - /// The king buffer of received message. - public delegate void MessageReceivedHandler(IClient client, KingBufferReader kingBuffer); + /// The king buffer reader of received message. + public delegate void MessageReceivedHandler(IClient client, IKingBufferReader reader); /// /// The delegate of client disconnected handler connection. @@ -74,10 +54,7 @@ public abstract class KingBaseClient : IClient #endregion - /// - /// Method responsible for send message to connected server. - /// - /// The king buffer of received message. - public abstract void SendMessage(KingBufferWriter kingBuffer); + /// + public abstract void SendMessage(IKingBufferWriter writer); } } diff --git a/src/KingNetwork.Server/KingTcpClient.cs b/src/KingNetwork.Server/Clients/TcpClient.cs similarity index 79% rename from src/KingNetwork.Server/KingTcpClient.cs rename to src/KingNetwork.Server/Clients/TcpClient.cs index 561ed8c..593f5a3 100644 --- a/src/KingNetwork.Server/KingTcpClient.cs +++ b/src/KingNetwork.Server/Clients/TcpClient.cs @@ -1,4 +1,5 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Net.Sockets; @@ -7,10 +8,30 @@ namespace KingNetwork.Server /// /// This class is responsible for represents the tcp client connection. /// - public class KingTcpClient : KingBaseClient + public class TcpClient : Client { + #region private members + + /// + /// The tcp client instance from client. + /// + protected Socket _socketClient; + + /// + /// The stream of tcp client. + /// + protected NetworkStream _stream; + + /// + /// The buffer of client connection. + /// + protected byte[] _buffer; + + #endregion + #region properties + /// public override bool IsConnected => _socketClient.Connected; #endregion @@ -18,14 +39,14 @@ public class KingTcpClient : KingBaseClient #region constructors /// - /// Creates a new instance of a . + /// Creates a new instance of a . /// /// The identifier number of connected client. /// The tcp client from connected client. /// The callback of message received handler implementation. /// The callback of client disconnected handler implementation. /// The max length of message buffer. - public KingTcpClient(ushort id, Socket socketClient, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer) + public TcpClient(ushort id, Socket socketClient, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer) { try { @@ -52,17 +73,14 @@ public KingTcpClient(ushort id, Socket socketClient, MessageReceivedHandler mess #region public methods implementation - /// - /// Method responsible for send message to client. - /// - /// The king buffer of received message. - public override void SendMessage(KingBufferWriter kingBuffer) + /// + public override void SendMessage(IKingBufferWriter writer) { try { if (IsConnected) { - _stream.Write(kingBuffer.BufferData, 0, kingBuffer.Length); + _stream.Write(writer.BufferData, 0, writer.Length); _stream.Flush(); } } diff --git a/src/KingNetwork.Server/KingUdpClient.cs b/src/KingNetwork.Server/Clients/UDPClient.cs similarity index 78% rename from src/KingNetwork.Server/KingUdpClient.cs rename to src/KingNetwork.Server/Clients/UDPClient.cs index f28cd85..3707dd4 100644 --- a/src/KingNetwork.Server/KingUdpClient.cs +++ b/src/KingNetwork.Server/Clients/UDPClient.cs @@ -1,4 +1,5 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Net; using System.Net.Sockets; @@ -6,15 +7,13 @@ namespace KingNetwork.Server { /// - /// This class is responsible for represents the tcp client connection. + /// This class is responsible for represents the udp client connection. /// - public class KingUdpClient : KingBaseClient + public class UDPClient : Client { #region properties - /// - /// The is connected flag.; - /// + /// public override bool IsConnected => _udpListener.Socket.Connected; #endregion @@ -36,14 +35,14 @@ public class KingUdpClient : KingBaseClient #region constructor /// - /// Creates a new instance of a . + /// Creates a new instance of a . /// /// The identifier number of connected client. /// The tcp client from connected client. /// The callback of message received handler implementation. /// The callback of client disconnected handler implementation. /// The max length of message buffer. - public KingUdpClient(ushort id, UdpNetworkListener socketClient, EndPoint remoteEndPoint, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer) + public UDPClient(ushort id, UdpNetworkListener socketClient, EndPoint remoteEndPoint, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer) { try { @@ -53,8 +52,6 @@ public KingUdpClient(ushort id, UdpNetworkListener socketClient, EndPoint remote _messageReceivedHandler = messageReceivedHandler; _clientDisconnectedHandler = clientDisconnectedHandler; - _buffer = new byte[maxMessageBuffer]; - Id = id; } catch (Exception ex) @@ -67,16 +64,13 @@ public KingUdpClient(ushort id, UdpNetworkListener socketClient, EndPoint remote #region public methods implementation - /// - /// Method responsible for send message to client. - /// - /// The king buffer of received message. - public override void SendMessage(KingBufferWriter kingBuffer) + /// + public override void SendMessage(IKingBufferWriter writer) { try { if (_udpListener.Socket != null) - _udpListener.Socket.BeginSendTo(kingBuffer.BufferData, 0, kingBuffer.BufferData.Length, SocketFlags.None, _remoteEndPoint, UdpSendCompleted, new Action(UdpSendCompleted)); + _udpListener.Socket.BeginSendTo(writer.BufferData, 0, writer.BufferData.Length, SocketFlags.None, _remoteEndPoint, UdpSendCompleted, new Action(UdpSendCompleted)); } catch (Exception ex) { diff --git a/src/KingNetwork.Server/KingWebSocketClient.cs b/src/KingNetwork.Server/Clients/WSClient.cs similarity index 79% rename from src/KingNetwork.Server/KingWebSocketClient.cs rename to src/KingNetwork.Server/Clients/WSClient.cs index c76a0c4..c6a41a1 100644 --- a/src/KingNetwork.Server/KingWebSocketClient.cs +++ b/src/KingNetwork.Server/Clients/WSClient.cs @@ -1,4 +1,5 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; using System; using System.Linq; using System.Net; @@ -10,7 +11,7 @@ namespace KingNetwork.Server /// /// This class is responsible for represents the websocket client connection. /// - public class KingWebSocketClient : KingBaseClient + public class WSClient : Client { #region private members @@ -38,6 +39,7 @@ public class KingWebSocketClient : KingBaseClient #region properties + /// public override bool IsConnected => _webSocket != null; #endregion @@ -45,15 +47,16 @@ public class KingWebSocketClient : KingBaseClient #region constructors /// - /// Creates a new instance of a . + /// Creates a new instance of a . /// + /// The identifier number of connected client. /// The listener type of client connection. /// The websocket connection. /// The websocket http listener context. /// The callback of message received handler implementation. /// The callback of client disconnected handler implementation. /// The max length of message buffer. - public KingWebSocketClient(NetworkListenerType listenerType, WebSocket ws, HttpListenerContext listenerContext, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer) + public WSClient(ushort id, NetworkListenerType listenerType, WebSocket ws, HttpListenerContext listenerContext, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer) { try { @@ -66,6 +69,8 @@ public KingWebSocketClient(NetworkListenerType listenerType, WebSocket ws, HttpL _messageReceivedHandler = messageReceivedHandler; _clientDisconnectedHandler = clientDisconnectedHandler; + Id = id; + WaitConnection(); } catch (Exception ex) @@ -78,22 +83,19 @@ public KingWebSocketClient(NetworkListenerType listenerType, WebSocket ws, HttpL #region public methods implementation - /// - /// Method responsible for send message to client. - /// - /// The king buffer of received message. - public override void SendMessage(KingBufferWriter kingBuffer) + /// + public override void SendMessage(IKingBufferWriter writer) { try { if (_listenerType == NetworkListenerType.WSText) { - var data = new ArraySegment(kingBuffer.BufferData, 4, kingBuffer.BufferData.Length - 4); + var data = new ArraySegment(writer.BufferData, 4, writer.BufferData.Length - 4); _webSocket.SendAsync(data, WebSocketMessageType.Text, true, CancellationToken.None); } else if (_listenerType == NetworkListenerType.WSBinary) { - var data = new ArraySegment(kingBuffer.BufferData); + var data = new ArraySegment(writer.BufferData); _webSocket.SendAsync(data, WebSocketMessageType.Binary, true, CancellationToken.None); } } @@ -107,8 +109,10 @@ public override void SendMessage(KingBufferWriter kingBuffer) #region private methods implementations - - public async void WaitConnection() + /// + /// This method is reponsible for wait for connections. + /// + private async void WaitConnection() { while (_webSocket.State == WebSocketState.Open) { @@ -122,20 +126,20 @@ public async void WaitConnection() { var data = _buff.Take(ret.Count).ToArray(); - var writter = KingBufferWriter.Create(); - writter.Write(data); + var writer = KingBufferWriter.Create(); + writer.Write(data); - var buffer = KingBufferReader.Create(writter.BufferData, 0, writter.Length); + var reader = KingBufferReader.Create(writer.BufferData, 0, writer.Length); - _messageReceivedHandler(this, buffer); + _messageReceivedHandler(this, reader); } } else if (ret.MessageType == WebSocketMessageType.Binary) { if (_listenerContext.Request.RemoteEndPoint != null) { - KingBufferReader buffer = KingBufferReader.Create(_buff.Take(ret.Count).ToArray(), 0, ret.Count); - _messageReceivedHandler(this, buffer); + var reader = KingBufferReader.Create(_buff.Take(ret.Count).ToArray(), 0, ret.Count); + _messageReceivedHandler(this, reader); } } else if (ret.MessageType == WebSocketMessageType.Close) diff --git a/src/KingNetwork.Server/Interfaces/IClient.cs b/src/KingNetwork.Server/Interfaces/IClient.cs index f6c3a92..e8d6f51 100644 --- a/src/KingNetwork.Server/Interfaces/IClient.cs +++ b/src/KingNetwork.Server/Interfaces/IClient.cs @@ -1,4 +1,5 @@ using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Server.Interfaces { @@ -25,7 +26,8 @@ public interface IClient /// /// Method responsible for send message to specific connected client. /// - /// The king buffer of received message. - void SendMessage(KingBufferWriter kingBuffer); + /// The king bufferwriter of received message. + void SendMessage(IKingBufferWriter writer); + } } \ No newline at end of file diff --git a/src/KingNetwork.Server/Interfaces/INetworkListener.cs b/src/KingNetwork.Server/Interfaces/INetworkListener.cs new file mode 100644 index 0000000..b08cdc0 --- /dev/null +++ b/src/KingNetwork.Server/Interfaces/INetworkListener.cs @@ -0,0 +1,25 @@ +using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; + +namespace KingNetwork.Server.Interfaces +{ + /// + /// This interface is responsible for represents the client. + /// + public interface INetworkListener + { + #region public methods implementation + + /// + /// This method is responsible for call the dispose implementation method. + /// + void Dispose(); + + /// + /// Method responsible for stop the tcp network listener. + /// + void Stop(); + + #endregion + } +} \ No newline at end of file diff --git a/src/KingNetwork.Server/Interfaces/IPacketHandler.cs b/src/KingNetwork.Server/Interfaces/IPacketHandler.cs index f5bedff..a4a34c8 100644 --- a/src/KingNetwork.Server/Interfaces/IPacketHandler.cs +++ b/src/KingNetwork.Server/Interfaces/IPacketHandler.cs @@ -1,4 +1,4 @@ -using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Server.Interfaces { @@ -11,7 +11,7 @@ internal interface IPacketHandler /// This method is responsible for receive the message from server packet handler. /// /// The connected client. - /// The king buffer received from message. - void HandleMessageData(IClient client, KingBufferReader kingBuffer); + /// The king buffer reader received from message. + void HandleMessageData(IClient client, IKingBufferReader reader); } } diff --git a/src/KingNetwork.Server/KingServer.cs b/src/KingNetwork.Server/KingServer.cs index aa96d9d..c87de16 100644 --- a/src/KingNetwork.Server/KingServer.cs +++ b/src/KingNetwork.Server/KingServer.cs @@ -2,10 +2,10 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Server { @@ -19,7 +19,7 @@ public class KingServer /// /// The network listener instance. /// - private NetworkListener _networkListener; + private INetworkListener _networkListener; /// /// The network dictionary list of server packet handlers. @@ -46,11 +46,6 @@ public class KingServer /// private readonly ushort _maxClientConnections; - /// - /// The counter for generation of client id. - /// - private int _counter = 0; - #endregion #region properties @@ -58,7 +53,7 @@ public class KingServer /// /// The callback of message received handler implementation. /// - public KingBaseClient.MessageReceivedHandler OnMessageReceivedHandler { get; set; } + public Client.MessageReceivedHandler OnMessageReceivedHandler { get; set; } /// /// The callback of client connnected handler implementation. @@ -68,7 +63,7 @@ public class KingServer /// /// The callback of client disconnected handler implementation. /// - public KingBaseClient.ClientDisconnectedHandler OnClientDisconnectedHandler { get; set; } + public Client.ClientDisconnectedHandler OnClientDisconnectedHandler { get; set; } /// /// The callback of started server handler implementation. @@ -84,8 +79,8 @@ public class KingServer /// The server packet handler delegate. /// /// The connected client. - /// The king buffer received from message. - public delegate void ServerPacketHandler(IClient client, KingBufferReader kingBuffer); + /// The king buffer reader from received message. + public delegate void ServerPacketHandler(IClient client, IKingBufferReader reader); /// /// The handler from callback of client connection. @@ -128,24 +123,19 @@ public KingServer(ushort port = 7171, ushort maxMessageBuffer = 4096, ushort max #region private methods implementation - /// - /// Method responsible for generation of identifier to new connected client. - /// - private ushort GetNewClientIdentifier() => (ushort)Interlocked.Increment(ref _counter); - /// /// Method responsible for execute the callback of message received from client in server. /// /// The connected client. /// The king buffer received from message. - private void OnMessageReceived(IClient client, KingBufferReader kingBuffer) + private void OnMessageReceived(IClient client, IKingBufferReader reader) { try { - if (kingBuffer.Length > 0 && _serverPacketHandlers.Count > 0 && _serverPacketHandlers.TryGetValue(kingBuffer.ReadByte(), out var serverHandler)) - serverHandler(client, kingBuffer); + if (reader.Length > 0 && _serverPacketHandlers.Count > 0 && _serverPacketHandlers.TryGetValue(reader.ReadByte(), out var serverHandler)) + serverHandler(client, reader); else - OnMessageReceivedHandler?.Invoke(client, kingBuffer); + OnMessageReceivedHandler?.Invoke(client, reader); } catch (Exception ex) { @@ -156,25 +146,20 @@ private void OnMessageReceived(IClient client, KingBufferReader kingBuffer) /// /// Method responsible for execute the callback of client connected in server. /// - /// The socket client object from connected client. - private void OnClientConnected(KingBaseClient socketClient) + /// The socket client object from connected client. + private void OnClientConnected(IClient client) { try { if (_clients.Count <= _maxClientConnections) { - //var client = new TcpClient(GetNewClientIdentifier(), socketClient, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer); - //_clients.Add(client.Id, client); - - socketClient.Id = GetNewClientIdentifier(); - _clients.Add(socketClient.Id, socketClient); - - OnClientConnectedHandler?.Invoke(socketClient); + _clients.Add(client.Id, client); + OnClientConnectedHandler?.Invoke(client); } else { //Implements Dispose - //socketClient.Dispose(); + //client.Dispose(); Console.WriteLine($"Max client connections {_maxClientConnections}."); } @@ -213,7 +198,12 @@ private async Task StartListenerAsync(CancellationToken cancellationToken, Netwo { try { - _networkListener = NetworkListenerFactory.CreateForType(listenerType, _port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer); + if (listenerType == NetworkListenerType.TCP) + _networkListener = new TcpNetworkListener(_port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer); + else if (listenerType == NetworkListenerType.UDP) + _networkListener = new UdpNetworkListener(_port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer); + else if (listenerType == NetworkListenerType.WSBinary || listenerType == NetworkListenerType.WSText) + _networkListener = new WebSocketNetworkListener(listenerType, _port, OnClientConnected, OnMessageReceived, OnClientDisconnected, _maxMessageBuffer); OnServerStartedHandler?.Invoke(); diff --git a/src/KingNetwork.Server/NetworkListener.cs b/src/KingNetwork.Server/Listeners/NetworkListener.cs similarity index 77% rename from src/KingNetwork.Server/NetworkListener.cs rename to src/KingNetwork.Server/Listeners/NetworkListener.cs index 2fe928f..f43b768 100644 --- a/src/KingNetwork.Server/NetworkListener.cs +++ b/src/KingNetwork.Server/Listeners/NetworkListener.cs @@ -1,13 +1,15 @@ -using System; +using KingNetwork.Server.Interfaces; +using System; using System.Net.Sockets; -using static KingNetwork.Server.KingBaseClient; +using System.Threading; +using static KingNetwork.Server.Client; namespace KingNetwork.Server { /// /// This class is responsible for representation of abstract network listener. /// - public abstract class NetworkListener : IDisposable + public abstract class NetworkListener : INetworkListener, IDisposable { #region private members @@ -16,9 +18,19 @@ public abstract class NetworkListener : IDisposable /// protected ClientConnectedHandler _clientConnectedHandler; + /// + /// The callback of message received handler implementation. + /// protected MessageReceivedHandler _messageReceivedHandler; + + /// + /// The callback of client disconnected handler implementation. + /// protected ClientDisconnectedHandler _clientDisconnectedHandler; + // + /// The max length of message buffer. + /// protected ushort _maxMessageBuffer; /// @@ -31,6 +43,11 @@ public abstract class NetworkListener : IDisposable /// private bool _disposedValue; + /// + /// The counter for generation of client id. + /// + private int _counter = 0; + #endregion #region delegates @@ -39,7 +56,7 @@ public abstract class NetworkListener : IDisposable /// The handler from callback of client connection. /// /// The socket client from connected client. - public delegate void ClientConnectedHandler(KingBaseClient socketClient); + public delegate void ClientConnectedHandler(Client socketClient); #endregion @@ -68,14 +85,10 @@ public NetworkListener(ushort port, ClientConnectedHandler clientConnectedHandle #region public methods implementation - /// - /// This method is responsible for call the dispose implementation method. - /// + /// public void Dispose() => Dispose(true); - /// - /// Method responsible for stop the tcp network listener. - /// + /// public void Stop() { try @@ -107,6 +120,11 @@ protected virtual void Dispose(bool disposing) } } + /// + /// Method responsible for generation of identifier to new connected client. + /// + protected ushort GetNewClientIdentifier() => (ushort)Interlocked.Increment(ref _counter); + #endregion } } diff --git a/src/KingNetwork.Server/TcpNetworkListener.cs b/src/KingNetwork.Server/Listeners/TcpNetworkListener.cs similarity index 90% rename from src/KingNetwork.Server/TcpNetworkListener.cs rename to src/KingNetwork.Server/Listeners/TcpNetworkListener.cs index 3acfe7b..fe549b7 100644 --- a/src/KingNetwork.Server/TcpNetworkListener.cs +++ b/src/KingNetwork.Server/Listeners/TcpNetworkListener.cs @@ -1,7 +1,7 @@ using System; using System.Net; using System.Net.Sockets; -using static KingNetwork.Server.KingBaseClient; +using static KingNetwork.Server.Client; namespace KingNetwork.Server { @@ -52,8 +52,8 @@ private void OnAccept(IAsyncResult asyncResult) { try { - //_clientConnectedHandler(_listener.EndAccept(asyncResult)); - var client = new KingTcpClient(0, _listener.EndAccept(asyncResult), _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer); + var clientId = GetNewClientIdentifier(); + var client = new TcpClient(clientId, _listener.EndAccept(asyncResult), _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer); _clientConnectedHandler(client); } catch(Exception ex) diff --git a/src/KingNetwork.Server/UdpNetworkListener.cs b/src/KingNetwork.Server/Listeners/UdpNetworkListener.cs similarity index 91% rename from src/KingNetwork.Server/UdpNetworkListener.cs rename to src/KingNetwork.Server/Listeners/UdpNetworkListener.cs index 63c639e..f1b8fe0 100644 --- a/src/KingNetwork.Server/UdpNetworkListener.cs +++ b/src/KingNetwork.Server/Listeners/UdpNetworkListener.cs @@ -4,7 +4,7 @@ using System.Net; using System.Net.Sockets; using System.Threading; -using static KingNetwork.Server.KingBaseClient; +using static KingNetwork.Server.Client; namespace KingNetwork.Server { @@ -27,7 +27,7 @@ public class UdpNetworkListener : NetworkListener /// /// The kingUdpClients list. /// - private Dictionary _kingUdpClients; + private Dictionary _kingUdpClients; #endregion @@ -48,7 +48,7 @@ public UdpNetworkListener(ushort port, ClientConnectedHandler clientConnectedHan { try { - _kingUdpClients = new Dictionary(); + _kingUdpClients = new Dictionary(); _listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _listener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)); @@ -99,7 +99,7 @@ private void ReceiveDataCallback(IAsyncResult asyncResult) Monitor.Enter(kingUdpClientsObj); bool hasClientConnection = false; - KingUdpClient kingUdpClient = null; + UDPClient kingUdpClient = null; try { @@ -116,7 +116,8 @@ private void ReceiveDataCallback(IAsyncResult asyncResult) } else if (array.Length == 9) { - var client = new KingUdpClient(0, this, endPoint, _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer); + var clientId = GetNewClientIdentifier(); + var client = new UDPClient(clientId, this, endPoint, _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer); _clientConnectedHandler(client); _kingUdpClients.Add(endPoint, client); diff --git a/src/KingNetwork.Server/WebSocketNetworkListener.cs b/src/KingNetwork.Server/Listeners/WebSocketNetworkListener.cs similarity index 92% rename from src/KingNetwork.Server/WebSocketNetworkListener.cs rename to src/KingNetwork.Server/Listeners/WebSocketNetworkListener.cs index 834ed7a..b63ac41 100644 --- a/src/KingNetwork.Server/WebSocketNetworkListener.cs +++ b/src/KingNetwork.Server/Listeners/WebSocketNetworkListener.cs @@ -3,7 +3,7 @@ using System.Linq; using System.Net; using System.Net.Sockets; -using static KingNetwork.Server.KingBaseClient; +using static KingNetwork.Server.Client; namespace KingNetwork.Server { @@ -80,7 +80,8 @@ private async void WaitForConnections() { var webSocket = (await listenerContext.AcceptWebSocketAsync(null)).WebSocket; - var client = new KingWebSocketClient(_listenerType, webSocket, listenerContext, _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer); + var clientId = GetNewClientIdentifier(); + var client = new WSClient(clientId, _listenerType, webSocket, listenerContext, _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer); _clientConnectedHandler(client); } else diff --git a/src/KingNetwork.Server/NetworkListenerFactory.cs b/src/KingNetwork.Server/NetworkListenerFactory.cs deleted file mode 100644 index 977c335..0000000 --- a/src/KingNetwork.Server/NetworkListenerFactory.cs +++ /dev/null @@ -1,22 +0,0 @@ -using KingNetwork.Shared; -using static KingNetwork.Server.KingBaseClient; -using static KingNetwork.Server.NetworkListener; - -namespace KingNetwork.Server -{ - public static class NetworkListenerFactory - { - public static NetworkListener CreateForType(NetworkListenerType listenerType, ushort port, ClientConnectedHandler clientConnectedHandler, - MessageReceivedHandler messageReceivedHandler, - ClientDisconnectedHandler clientDisconnectedHandler, - ushort maxMessageBuffer) - { - if (listenerType == NetworkListenerType.TCP) - return new TcpNetworkListener(port, clientConnectedHandler, messageReceivedHandler, clientDisconnectedHandler, maxMessageBuffer); - else if (listenerType == NetworkListenerType.WSBinary || listenerType == NetworkListenerType.WSText) - return new WebSocketNetworkListener(listenerType, port, clientConnectedHandler, messageReceivedHandler, clientDisconnectedHandler, maxMessageBuffer); - - return new UdpNetworkListener(port, clientConnectedHandler, messageReceivedHandler, clientDisconnectedHandler, maxMessageBuffer); - } - } -} diff --git a/src/KingNetwork.Server/PacketHandler.cs b/src/KingNetwork.Server/PacketHandler.cs index 570c43b..eec936a 100644 --- a/src/KingNetwork.Server/PacketHandler.cs +++ b/src/KingNetwork.Server/PacketHandler.cs @@ -1,18 +1,12 @@ using KingNetwork.Server.Interfaces; -using KingNetwork.Shared; +using KingNetwork.Shared.Interfaces; namespace KingNetwork.Server { - /// - /// This class is responsible for representation of abstract server packet handler. - /// + /// public abstract class PacketHandler : IPacketHandler { - /// - /// This method is responsible for receive the message from server packet handler. - /// - /// The connected client. - /// The king buffer received from message. - public abstract void HandleMessageData(IClient client, KingBufferReader kingBuffer); + /// + public abstract void HandleMessageData(IClient client, IKingBufferReader reader); } } diff --git a/src/KingNetwork.Shared/Interfaces/IKingBufferReader.cs b/src/KingNetwork.Shared/Interfaces/IKingBufferReader.cs new file mode 100644 index 0000000..174f536 --- /dev/null +++ b/src/KingNetwork.Shared/Interfaces/IKingBufferReader.cs @@ -0,0 +1,235 @@ +using System; +using System.Text; + +namespace KingNetwork.Shared.Interfaces +{ + /// + /// This interface is responsible for represents the king buffer reader interface of application. + /// + public interface IKingBufferReader + { + #region properties + + /// + /// The encoding value to strings. + /// + Encoding Encoding { get; } + + /// + /// The length value of buffer. + /// + int Length { get; } + + /// + /// The position value of buffer. + /// + int Position { get; } + + #endregion + + #region methods declaration + + /// + /// Method responsible for read a byte value from buffer. + /// + /// The byte value from buffer. + byte ReadByte(); + + /// + /// Method responsible for read a char value from buffer. + /// + /// The char value from buffer. + char ReadChar(); + + /// + /// Method responsible for read a bool value from buffer. + /// + /// The bool value from buffer. + bool ReadBoolean(); + + /// + /// Method responsible for read a double value from buffer. + /// + /// The double value from buffer. + double ReadDouble(); + + /// + /// Method responsible for read a short value from buffer. + /// + /// The short value from buffer. + short ReadInt16(); + + /// + /// Method responsible for read a int value from buffer. + /// + /// The int value from buffer. + int ReadInt32(); + + /// + /// Method responsible for read a long value from buffer. + /// + /// The long value from buffer. + long ReadInt64(); + + /// + /// Method responsible for sbyte a char value from buffer. + /// + /// The sbyte value from buffer. + sbyte ReadSByte(); + + /// + /// Method responsible for read a float value from buffer. + /// + /// The float value from buffer. + float ReadSingle(); + + /// + /// Method responsible for read a string value from buffer. + /// + /// The string value from buffer. + string ReadString(); + + /// + /// Method responsible for read a string value from buffer. + /// + /// The encoding value to read string in the buffer. + /// The string value from buffer. + string ReadString(Encoding encoding); + + /// + /// Method responsible for read a ushort value from buffer. + /// + /// The ushort value from buffer. + ushort ReadUInt16(); + + /// + /// Method responsible for read a uint value from buffer. + /// + /// The uint value from buffer. + uint ReadUInt32(); + + /// + /// Method responsible for read a ulong value from buffer. + /// + /// The ulong value from buffer. + ulong ReadUInt64(); + + /// + /// Method responsible for read a message packet value from buffer using generics. + /// + /// Returns a generic representation of message packet value from buffer. + TPacket ReadMessagePacket() where TPacket : IConvertible; + + /// + /// Method responsible for read a byte array value from buffer. + /// + /// The byte array value from buffer. + byte[] ReadBytes(); + + /// + /// Method responsible for read a char array value from buffer. + /// + /// The char array value from buffer. + char[] ReadChars(); + + /// + /// Method responsible for read a char array value from buffer. + /// + /// The encoding value to read string in the buffer. + /// The char array value from buffer. + char[] ReadChars(Encoding encoding); + + /// + /// Method responsible for read a bool array value from buffer. + /// + /// The bool array value from buffer. + bool[] ReadBooleans(); + + /// + /// Method responsible for read a double array value from buffer. + /// + /// The double array value from buffer. + double[] ReadDoubles(); + + /// + /// Method responsible for read a short array value from buffer. + /// + /// The short array value from buffer. + short[] ReadInt16s(); + + /// + /// Method responsible for read a int array value from buffer. + /// + /// The int array value from buffer. + int[] ReadInt32s(); + + /// + /// Method responsible for read a long array value from buffer. + /// + /// The long array value from buffer. + long[] ReadInt64s(); + + /// + /// Method responsible for read a sbyte array value from buffer. + /// + /// The sbyte array value from buffer. + sbyte[] ReadSBytes(); + + /// + /// Method responsible for read a float array value from buffer. + /// + /// The float array value from buffer. + float[] ReadSingles(); + + /// + /// Method responsible for read a string array value from buffer. + /// + /// The string array value from buffer. + string[] ReadStrings(); + + /// + /// Method responsible for read a ushort array value from buffer. + /// + /// The ushort array value from buffer. + ushort[] ReadUInt16s(); + + /// + /// Method responsible for read a uint array value from buffer. + /// + /// The uint array value from buffer. + uint[] ReadUInt32s(); + + /// + /// Method responsible for read a ulong array value from buffer. + /// + /// The ulong array value from buffer. + ulong[] ReadUInt64s(); + + /// + /// Method responsible for read a raw data value from buffer. + /// + /// The length of raw data to read from buffer. + /// The byte array value from buffer. + byte[] ReadRaw(int length); + + /// + /// Method responsible for read a raw data into data buffer. + /// + /// The buffer array value. + /// The offset of byte array data. + /// The length of byte array data. + void ReadRawInto(byte[] buffer, int offset, int length); + + /// + /// Method responsible for reset the buffer. + /// + void Reset(); + + /// + /// Method responsible for dispose the instance. + /// + void Dispose(); + + #endregion + } +} diff --git a/src/KingNetwork.Shared/IKingBufferWriter.cs b/src/KingNetwork.Shared/Interfaces/IKingBufferWriter.cs similarity index 92% rename from src/KingNetwork.Shared/IKingBufferWriter.cs rename to src/KingNetwork.Shared/Interfaces/IKingBufferWriter.cs index 3c7c4b8..87fb392 100644 --- a/src/KingNetwork.Shared/IKingBufferWriter.cs +++ b/src/KingNetwork.Shared/Interfaces/IKingBufferWriter.cs @@ -1,13 +1,37 @@ using System; using System.Text; -namespace KingNetwork.Shared +namespace KingNetwork.Shared.Interfaces { /// /// This interface is responsible for represents the king buffer writer interface of application. /// public interface IKingBufferWriter { + #region properties + + /// + /// The encoding value to strings. + /// + Encoding Encoding { get; } + + /// + /// The byte array buffer. + /// + byte[] BufferData { get; } + + /// + /// The length value of buffer. + /// + int Length { get; } + + /// + /// The capacity value of buffer. + /// + int Capacity { get; } + + #endregion + #region methods declaration /// @@ -199,6 +223,11 @@ public interface IKingBufferWriter /// void Reset(); + /// + /// Method responsible for dispose the instance. + /// + void Dispose(); + #endregion } } diff --git a/src/KingNetwork.Shared/KingBufferReader.cs b/src/KingNetwork.Shared/KingBufferReader.cs index d5a956c..2051749 100644 --- a/src/KingNetwork.Shared/KingBufferReader.cs +++ b/src/KingNetwork.Shared/KingBufferReader.cs @@ -1,4 +1,5 @@ -using System; +using KingNetwork.Shared.Interfaces; +using System; using System.IO; using System.Text; @@ -7,7 +8,7 @@ namespace KingNetwork.Shared /// /// This class is responsible for represents the buffer of application. /// - public class KingBufferReader : IDisposable + public class KingBufferReader : IKingBufferReader, IDisposable { #region private members @@ -19,31 +20,29 @@ public class KingBufferReader : IDisposable /// /// The byte array data of buffer. /// - private byte[] bytes; + private byte[] _bytes; /// /// The byte array buffer. /// - private int dataOffset; + private int _dataOffset; /// /// The byte array buffer. /// private byte[] _buffer = new byte[8]; - - /// - /// The encoding value to strings. - /// - public Encoding Encoding { get; set; } - - /// - /// The length value of buffer. - /// + + #endregion + + #region properties + + /// + public Encoding Encoding { get; private set; } + + /// public int Length { get; private set; } - /// - /// The position value of buffer. - /// + /// public int Position { get; private set; } #endregion @@ -76,40 +75,28 @@ public static KingBufferReader Create(byte[] bytes, int dataOffset, int dataLeng #region public methods implementation - /// - /// Method responsible for read a byte value from buffer. - /// - /// The byte value from buffer. + /// public byte ReadByte() { if (Position >= Length) throw new EndOfStreamException(); - return bytes[dataOffset + Position++]; + return _bytes[_dataOffset + Position++]; } - /// - /// Method responsible for read a char value from buffer. - /// - /// The char value from buffer. + /// public char ReadChar() => ReadChars()[0]; - /// - /// Method responsible for read a bool value from buffer. - /// - /// The bool value from buffer. + /// public bool ReadBoolean() => ReadByte() == 1; - /// - /// Method responsible for read a double value from buffer. - /// - /// The double value from buffer. + /// public double ReadDouble() { if (Position + 8 > Length) throw new EndOfStreamException(); - Buffer.BlockCopy(bytes, dataOffset + Position, _buffer, 0, 8); + Buffer.BlockCopy(_bytes, _dataOffset + Position, _buffer, 0, 8); Position += 8; if (BitConverter.IsLittleEndian) @@ -118,64 +105,49 @@ public double ReadDouble() return BitConverter.ToDouble(_buffer, 0); } - /// - /// Method responsible for read a short value from buffer. - /// - /// The short value from buffer. + /// public short ReadInt16() { if (Position + 2 > Length) throw new EndOfStreamException(); - short result = ReadInt16(bytes, dataOffset + Position); + short result = ReadInt16(_bytes, _dataOffset + Position); Position += 2; return result; } - /// - /// Method responsible for read a int value from buffer. - /// - /// The int value from buffer. + /// public int ReadInt32() { if (Position + 4 > Length) throw new EndOfStreamException(); - int result = ReadInt32(bytes, dataOffset + Position); + int result = ReadInt32(_bytes, _dataOffset + Position); Position += 4; return result; } - /// - /// Method responsible for read a long value from buffer. - /// - /// The long value from buffer. + /// public long ReadInt64() { if (Position + 8 > Length) throw new EndOfStreamException(); - long result = ReadInt64(bytes, dataOffset + Position); + long result = ReadInt64(_bytes, _dataOffset + Position); Position += 8; return result; } - /// - /// Method responsible for sbyte a char value from buffer. - /// - /// The sbyte value from buffer. + /// public sbyte ReadSByte() => (sbyte)ReadByte(); - /// - /// Method responsible for read a float value from buffer. - /// - /// The float value from buffer. + /// public float ReadSingle() { if (Position + 4 > Length) throw new EndOfStreamException(); - Buffer.BlockCopy(bytes, dataOffset + Position, _buffer, 0, 4); + Buffer.BlockCopy(_bytes, _dataOffset + Position, _buffer, 0, 4); Position += 4; if (BitConverter.IsLittleEndian) @@ -184,114 +156,82 @@ public float ReadSingle() return BitConverter.ToSingle(_buffer, 0); } - /// - /// Method responsible for read a string value from buffer. - /// - /// The string value from buffer. + /// public string ReadString() => ReadString(Encoding); - /// - /// Method responsible for read a string value from buffer. - /// - /// The encoding value to read string in the buffer. - /// The string value from buffer. + /// public string ReadString(Encoding encoding) { byte[] array = ReadBytes(); return encoding.GetString(array); } - /// - /// Method responsible for read a ushort value from buffer. - /// - /// The ushort value from buffer. + /// public ushort ReadUInt16() { if (Position + 2 > Length) throw new EndOfStreamException(); - ushort result = ReadUInt16(bytes, dataOffset + Position); + ushort result = ReadUInt16(_bytes, _dataOffset + Position); Position += 2; return result; } - /// - /// Method responsible for read a uint value from buffer. - /// - /// The uint value from buffer. + /// public uint ReadUInt32() { if (Position + 4 > Length) throw new EndOfStreamException(); - uint result = ReadUInt32(bytes, dataOffset + Position); + uint result = ReadUInt32(_bytes, _dataOffset + Position); Position += 4; return result; } - /// - /// Method responsible for read a ulong value from buffer. - /// - /// The ulong value from buffer. + /// public ulong ReadUInt64() { if (Position + 8 > Length) throw new EndOfStreamException(); - ulong result = ReadUInt64(bytes, dataOffset + Position); + ulong result = ReadUInt64(_bytes, _dataOffset + Position); Position += 8; return result; } - /// - /// Method responsible for read a message packet value from buffer using generics. - /// - /// Returns a generic representation of message packet value from buffer. + /// public TPacket ReadMessagePacket() where TPacket : IConvertible => (TPacket)(IConvertible)ReadByte(); - /// - /// Method responsible for read a byte array value from buffer. - /// - /// The byte array value from buffer. + /// public byte[] ReadBytes() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num > Length) throw new EndOfStreamException("Elements exceeded bounds"); byte[] array = new byte[num]; - Buffer.BlockCopy(bytes, dataOffset + Position + 4, array, 0, num); + Buffer.BlockCopy(_bytes, _dataOffset + Position + 4, array, 0, num); Position += 4 + num; return array; } - /// - /// Method responsible for read a char array value from buffer. - /// - /// The char array value from buffer. + /// public char[] ReadChars() => ReadChars(Encoding); - /// - /// Method responsible for read a char array value from buffer. - /// - /// The encoding value to read string in the buffer. - /// The char array value from buffer. + /// public char[] ReadChars(Encoding encoding) => encoding.GetChars(ReadBytes()); - /// - /// Method responsible for read a bool array value from buffer. - /// - /// The bool array value from buffer. + /// public bool[] ReadBooleans() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); int num2 = (int)Math.Ceiling((double)num / 8.0); if (Position + 4 + num2 > Length) @@ -302,7 +242,7 @@ public bool[] ReadBooleans() for (int i = 0; i < num2; i++) { - byte b = bytes[dataOffset + Position + 4 + i]; + byte b = _bytes[_dataOffset + Position + 4 + i]; for (int j = 0; j < 8; j++) { @@ -318,27 +258,24 @@ public bool[] ReadBooleans() return array; } - /// - /// Method responsible for read a double array value from buffer. - /// - /// The double array value from buffer. + /// public double[] ReadDoubles() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 8 > Length) throw new EndOfStreamException("Elements exceeded bounds"); double[] array = new double[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - Buffer.BlockCopy(bytes, num3, _buffer, 0, 8); + Buffer.BlockCopy(_bytes, num3, _buffer, 0, 8); if (BitConverter.IsLittleEndian) Array.Reverse(_buffer, 0, 8); @@ -352,27 +289,24 @@ public double[] ReadDoubles() return array; } - /// - /// Method responsible for read a short array value from buffer. - /// - /// The short array value from buffer. + /// public short[] ReadInt16s() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 2 > Length) throw new EndOfStreamException("Elements exceeded bounds"); short[] array = new short[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - array[num2] = ReadInt16(bytes, num3); + array[num2] = ReadInt16(_bytes, num3); num2++; num3 += 2; } @@ -381,27 +315,24 @@ public short[] ReadInt16s() return array; } - /// - /// Method responsible for read a int array value from buffer. - /// - /// The int array value from buffer. + /// public int[] ReadInt32s() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 4 > Length) throw new EndOfStreamException("Elements exceeded bounds"); int[] array = new int[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - array[num2] = ReadInt32(bytes, num3); + array[num2] = ReadInt32(_bytes, num3); num2++; num3 += 4; } @@ -410,27 +341,24 @@ public int[] ReadInt32s() return array; } - /// - /// Method responsible for read a long array value from buffer. - /// - /// The long array value from buffer. + /// public long[] ReadInt64s() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 8 > Length) throw new EndOfStreamException("Elements exceeded bounds"); long[] array = new long[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - array[num2] = ReadInt64(bytes, num3); + array[num2] = ReadInt64(_bytes, num3); num2++; num3 += 8; } @@ -439,48 +367,42 @@ public long[] ReadInt64s() return array; } - /// - /// Method responsible for read a sbyte array value from buffer. - /// - /// The sbyte array value from buffer. + /// public sbyte[] ReadSBytes() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num > Length) throw new EndOfStreamException("Elements exceeded bounds"); sbyte[] array = new sbyte[num]; - Buffer.BlockCopy(bytes, dataOffset + Position + 4, array, 0, num); + Buffer.BlockCopy(_bytes, _dataOffset + Position + 4, array, 0, num); Position += 4 + num; return array; } - /// - /// Method responsible for read a float array value from buffer. - /// - /// The float array value from buffer. + /// public float[] ReadSingles() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 4 > Length) throw new EndOfStreamException("Elements exceeded bounds"); float[] array = new float[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - Buffer.BlockCopy(bytes, num3, _buffer, 0, 4); + Buffer.BlockCopy(_bytes, num3, _buffer, 0, 4); if (BitConverter.IsLittleEndian) Array.Reverse(_buffer, 0, 4); @@ -494,16 +416,13 @@ public float[] ReadSingles() return array; } - /// - /// Method responsible for read a string array value from buffer. - /// - /// The string array value from buffer. + /// public string[] ReadStrings() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); Position += 4; string[] array = new string[num]; @@ -513,27 +432,24 @@ public string[] ReadStrings() return array; } - /// - /// Method responsible for read a ushort array value from buffer. - /// - /// The ushort array value from buffer. + /// public ushort[] ReadUInt16s() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 2 > Length) throw new EndOfStreamException("Elements exceeded bounds"); ushort[] array = new ushort[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - array[num2] = ReadUInt16(bytes, num3); + array[num2] = ReadUInt16(_bytes, num3); num2++; num3 += 2; } @@ -542,27 +458,24 @@ public ushort[] ReadUInt16s() return array; } - /// - /// Method responsible for read a uint array value from buffer. - /// - /// The uint array value from buffer. + /// public uint[] ReadUInt32s() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 4 > Length) throw new EndOfStreamException("Elements exceeded bounds"); uint[] array = new uint[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - array[num2] = ReadUInt32(bytes, num3); + array[num2] = ReadUInt32(_bytes, num3); num2++; num3 += 4; } @@ -571,27 +484,24 @@ public uint[] ReadUInt32s() return array; } - /// - /// Method responsible for read a ulong array value from buffer. - /// - /// The ulong array value from buffer. + /// public ulong[] ReadUInt64s() { if (Position + 4 > Length) throw new EndOfStreamException("Length parameter exceeded bounds"); - int num = ReadInt32(bytes, dataOffset + Position); + int num = ReadInt32(_bytes, _dataOffset + Position); if (Position + 4 + num * 8 > Length) throw new EndOfStreamException("Elements exceeded bounds"); ulong[] array = new ulong[num]; int num2 = 0; - int num3 = dataOffset + Position + 4; + int num3 = _dataOffset + Position + 4; while (num2 < num) { - array[num2] = ReadUInt64(bytes, num3); + array[num2] = ReadUInt64(_bytes, num3); num2++; num3 += 8; } @@ -600,11 +510,7 @@ public ulong[] ReadUInt64s() return array; } - /// - /// Method responsible for read a raw data value from buffer. - /// - /// The length of raw data to read from buffer. - /// The byte array value from buffer. + /// public byte[] ReadRaw(int length) { if (Position + length > Length) @@ -615,24 +521,17 @@ public byte[] ReadRaw(int length) return result; } - /// - /// Method responsible for read a raw data into data buffer. - /// - /// The buffer array value. - /// The offset of byte array data. - /// The length of byte array data. + /// public void ReadRawInto(byte[] buffer, int offset, int length) { if (Position + length > Length) throw new EndOfStreamException(); - Buffer.BlockCopy(bytes, dataOffset + Position, buffer, offset, length); + Buffer.BlockCopy(_bytes, _dataOffset + Position, buffer, offset, length); Position += length; } - /// - /// Method responsible for reset the buffer. - /// + /// public void Reset() { _buffer = new byte[8]; @@ -642,9 +541,7 @@ public void Reset() Encoding = Encoding.UTF8; } - /// - /// Method responsible for dispose the instance. - /// + /// public void Dispose() { KingPoolManager.DisposeKingBufferReader(this); @@ -681,9 +578,10 @@ protected virtual void Dispose(bool disposing) /// The dataLength of byte array data. private void Initialize(byte[] bytes, int dataOffset, int dataLength) { + _bytes = bytes; + _dataOffset = dataOffset; + Encoding = Encoding.UTF8; - this.bytes = bytes; - this.dataOffset = dataOffset; Length = dataLength; Position = 0; } diff --git a/src/KingNetwork.Shared/KingBufferWriter.cs b/src/KingNetwork.Shared/KingBufferWriter.cs index cecd708..aec7ef4 100644 --- a/src/KingNetwork.Shared/KingBufferWriter.cs +++ b/src/KingNetwork.Shared/KingBufferWriter.cs @@ -1,4 +1,5 @@ -using System; +using KingNetwork.Shared.Interfaces; +using System; using System.Text; namespace KingNetwork.Shared @@ -20,24 +21,20 @@ public class KingBufferWriter : IKingBufferWriter, IDisposable /// private byte[] _buffer; - /// - /// The encoding value to strings. - /// - public Encoding Encoding { get; set; } + #endregion - /// - /// The byte array buffer. - /// + #region properties + + /// public byte[] BufferData => _buffer; - /// - /// The length value of buffer. - /// - public int Length { get; set; } + /// + public Encoding Encoding { get; private set; } - /// - /// The capacity value of buffer. - /// + /// + public int Length { get; private set; } + + /// public int Capacity => _buffer.Length; #endregion @@ -102,36 +99,24 @@ public static KingBufferWriter Create(int initialCapacity, Encoding encoding) #region public methods implementation - /// - /// Method responsible for write a byte value in the buffer. - /// - /// The byte value to write in the buffer. + /// public void Write(byte value) { EnsureCapacity(1); _buffer[Length++] = value; } - /// - /// Method responsible for write a char value in the buffer. - /// - /// The char value to write in the buffer. + /// public void Write(char value) => Write(new char[1] { value }); - /// - /// Method responsible for write a bool value in the buffer. - /// - /// The bool value to write in the buffer. + /// public void Write(bool value) { EnsureCapacity(1); Write((byte)(value ? 1 : 0)); } - /// - /// Method responsible for write a double value in the buffer. - /// - /// The double value to write in the buffer. + /// public void Write(double value) { byte[] bytes = BitConverter.GetBytes(value); @@ -144,10 +129,7 @@ public void Write(double value) Length += 8; } - /// - /// Method responsible for write a short value in the buffer. - /// - /// The short value to write in the buffer. + /// public void Write(short value) { EnsureCapacity(2); @@ -155,10 +137,7 @@ public void Write(short value) Length += 2; } - /// - /// Method responsible for write a int value in the buffer. - /// - /// The int value to write in the buffer. + /// public void Write(int value) { EnsureCapacity(4); @@ -166,10 +145,7 @@ public void Write(int value) Length += 4; } - /// - /// Method responsible for write a long value in the buffer. - /// - /// The long value to write in the buffer. + /// public void Write(long value) { EnsureCapacity(8); @@ -177,19 +153,13 @@ public void Write(long value) Length += 8; } - /// - /// Method responsible for write a sbyte value in the buffer. - /// - /// The sbyte value to write in the buffer. + /// public void Write(sbyte value) { Write((byte)value); } - /// - /// Method responsible for write a float value in the buffer. - /// - /// The float value to write in the buffer. + /// public void Write(float value) { byte[] bytes = BitConverter.GetBytes(value); @@ -202,10 +172,7 @@ public void Write(float value) Length += 4; } - /// - /// Method responsible for write a ushort value in the buffer. - /// - /// The ushort value to write in the buffer. + /// public void Write(ushort value) { EnsureCapacity(2); @@ -213,10 +180,7 @@ public void Write(ushort value) Length += 2; } - /// - /// Method responsible for write a uint value in the buffer. - /// - /// The uint value to write in the buffer. + /// public void Write(uint value) { EnsureCapacity(4); @@ -224,10 +188,7 @@ public void Write(uint value) Length += 4; } - /// - /// Method responsible for write a ulong value in the buffer. - /// - /// The ulong value to write in the buffer. + /// public void Write(ulong value) { EnsureCapacity(8); @@ -235,33 +196,20 @@ public void Write(ulong value) Length += 8; } - /// - /// Method responsible for write a string value in the buffer. - /// - /// The string value to write in the buffer. + /// public void Write(string value) => Write(value, Encoding); - /// - /// Method responsible for write a byte value in the buffer. - /// - /// The byte value to write in the buffer. - /// The encoding value to write char array in the buffer. + /// public void Write(string value, Encoding encoding) => Write(encoding.GetBytes(value)); - /// - /// Method responsible for write a generic packet value in the buffer. - /// - /// The generic packet value to write in the buffer. + /// public void Write(TPacket packet) where TPacket : IConvertible { if (Enum.IsDefined(typeof(TPacket), packet)) Write((byte)(IConvertible)packet); } - /// - /// Method responsible for write a byte array values in the buffer. - /// - /// The byte array values to write in the buffer. + /// public void Write(byte[] value) { EnsureCapacity(4 + value.Length); @@ -272,23 +220,13 @@ public void Write(byte[] value) Length += 4 + value.Length; } - /// - /// Method responsible for write a char array values in the buffer. - /// - /// The char array values to write in the buffer. + /// public void Write(char[] value) => Write(value, Encoding); - /// - /// Method responsible for write a char array values in the buffer. - /// - /// The char array values to write in the buffer. - /// The encoding value to write char array in the buffer. + /// public void Write(char[] value, Encoding encoding) => Write(encoding.GetBytes(value)); - /// - /// Method responsible for write a bool array values in the buffer. - /// - /// The bool array values to write in the buffer. + /// public void Write(bool[] value) { int num = (int)Math.Ceiling((double)value.Length / 8.0); @@ -317,10 +255,7 @@ public void Write(bool[] value) Length += 4 + num; } - /// - /// Method responsible for write a double array values in the buffer. - /// - /// The double array values to write in the buffer. + /// public void Write(double[] value) { EnsureCapacity(4 + value.Length * 8); @@ -345,10 +280,7 @@ public void Write(double[] value) Length += 4 + value.Length * 8; } - /// - /// Method responsible for write a short array values in the buffer. - /// - /// The short array values to write in the buffer. + /// public void Write(short[] value) { EnsureCapacity(4 + value.Length * 2); @@ -367,10 +299,7 @@ public void Write(short[] value) Length += 4 + value.Length * 2; } - /// - /// Method responsible for write a int array values in the buffer. - /// - /// The int array values to write in the buffer. + /// public void Write(int[] value) { EnsureCapacity(4 + value.Length * 4); @@ -390,10 +319,7 @@ public void Write(int[] value) Length += 4 + value.Length * 4; } - /// - /// Method responsible for write a long array values in the buffer. - /// - /// The long array values to write in the buffer. + /// public void Write(long[] value) { EnsureCapacity(4 + value.Length * 8); @@ -413,10 +339,7 @@ public void Write(long[] value) Length += 4 + value.Length * 8; } - /// - /// Method responsible for write a sbyte array values in the buffer. - /// - /// The sbyte array values to write in the buffer. + /// public void Write(sbyte[] value) { EnsureCapacity(4 + value.Length); @@ -427,10 +350,7 @@ public void Write(sbyte[] value) Length += 4 + value.Length; } - /// - /// Method responsible for write a float array values in the buffer. - /// - /// The float array value to write in the buffer. + /// public void Write(float[] value) { EnsureCapacity(4 + value.Length * 4); @@ -455,10 +375,7 @@ public void Write(float[] value) Length += 4 + value.Length * 4; } - /// - /// Method responsible for write a string array values in the buffer. - /// - /// The string array values to write in the buffer. + /// public void Write(string[] value) { EnsureCapacity(4); @@ -470,10 +387,7 @@ public void Write(string[] value) Write(value2); } - /// - /// Method responsible for write a ushort array values in the buffer. - /// - /// The ushort array values to write in the buffer. + /// public void Write(ushort[] value) { EnsureCapacity(4 + value.Length * 2); @@ -493,10 +407,7 @@ public void Write(ushort[] value) Length += 4 + value.Length * 2; } - /// - /// Method responsible for write a uint array value in the buffer. - /// - /// The uint array values to write in the buffer. + /// public void Write(uint[] value) { EnsureCapacity(4 + value.Length * 4); @@ -516,10 +427,7 @@ public void Write(uint[] value) Length += 4 + value.Length * 4; } - /// - /// Method responsible for write a ulong array values in the buffer. - /// - /// The ulong array values to write in the buffer. + /// public void Write(ulong[] value) { EnsureCapacity(4 + value.Length * 8); @@ -538,12 +446,7 @@ public void Write(ulong[] value) Length += 4 + value.Length * 8; } - /// - /// Method responsible for write a byte array raw values in the buffer. - /// - /// The byte array raw values to write in the buffer. - /// The offset value to write raw in the buffer. - /// The length value to write raw in the buffer. + /// public void WriteRaw(byte[] bytes, int offset, int length) { EnsureCapacity(length); @@ -551,9 +454,7 @@ public void WriteRaw(byte[] bytes, int offset, int length) Length += length; } - /// - /// Method responsible for reset the buffer. - /// + /// public void Reset() { _buffer = new byte[16]; @@ -562,9 +463,7 @@ public void Reset() Encoding = Encoding.UTF8; } - /// - /// Method responsible for dispose the instance. - /// + /// public void Dispose() { KingPoolManager.DisposeKingBufferWriter(this); diff --git a/src/KingNetwork.Shared/KingNetwork.Shared.csproj b/src/KingNetwork.Shared/KingNetwork.Shared.csproj index e5344cf..f2b0623 100644 --- a/src/KingNetwork.Shared/KingNetwork.Shared.csproj +++ b/src/KingNetwork.Shared/KingNetwork.Shared.csproj @@ -2,7 +2,7 @@ netstandard2.0 - 1.0.2 + 1.0.3 KingNetwork is an open source library to facilitate the creation and communication of clients and servers through TCP, UDP and Web sockets. Felipe Muniz (Mun1z) LICENSE.md