diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f019b51..e243943 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,21 +10,24 @@ jobs: - name: Checkout uses: actions/checkout@v1 - + - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: 3.0.100 - + dotnet-version: 3.1.100 + - name: Build Release id: build_release run: | - VERSION_FILE=${{ github.workspace }}/services.version + VERSION_FILE=${{ github.workspace }}/.version VERSION=$(<"$VERSION_FILE") echo ::set-env name=VERSION::$VERSION + echo ::set-env name=VERSION_E::$(echo ${GITHUB_SHA} | cut -c1-8) mkdir ./release for RUNTIME in win-x86 win-x64 linux-x64 osx-x64; do - dotnet publish Arrowgene.Services/Arrowgene.Services.csproj /p:Version=$VERSION /p:FromMSBuild=true --runtime $RUNTIME --configuration Release --output ./publish/$RUNTIME-$VERSION + # Server + dotnet publish Arrowgene.Services/Arrowgene.Services.csproj --self-contained true /p:PublishTrimmed=true /p:Version=$VERSION /p:FromMSBuild=true --runtime $RUNTIME --configuration Release --output ./publish/$RUNTIME-$VERSION + # Pack tar cjf ./release/$RUNTIME-$VERSION.tar.gz ./publish/$RUNTIME-$VERSION done @@ -33,16 +36,16 @@ jobs: run: | dotnet pack Arrowgene.Services/Arrowgene.Services.csproj --output ../nupkgs /p:Version=${{ env.VERSION }} curl -vX PUT -u "sebastian-heinz:${{ secrets.GITHUB_TOKEN }}" -F package=@../nupkgs/Arrowgene.Services.${{ env.VERSION }}.nupkg https://nuget.pkg.github.com/sebastian-heinz/ - dotnet nuget push ../nupkgs/Arrowgene.Services.${{ env.VERSION }}.nupkg --api-key ${{ secrets.NUGET_DEPLOY_KEY }} --source https://www.nuget.org/api/v2/package - + dotnet nuget push ../nupkgs/Arrowgene.Services.${{ env.VERSION }}.nupkg --source https://www.nuget.org/api/v2/package --api-key ${{ secrets.NUGET_DEPLOY_KEY }} + - name: Create Release id: create_release uses: actions/create-release@v1.0.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - tag_name: release-${{ env.VERSION }} - release_name: Release ${{ env.VERSION }} + tag_name: release-${{ env.VERSION }}-${{ env.VERSION_E }} + release_name: Release ${{ env.VERSION }}-${{ env.VERSION_E }} draft: false prerelease: false @@ -53,9 +56,9 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./release/win-x86-${{ env.VERSION }}.tar.gz - asset_name: win-x86-${{ env.VERSION }}-${{ env.VERSION }}.tar.gz + asset_name: win-x86-${{ env.VERSION }}-${{ env.VERSION_E }}.tar.gz asset_content_type: application/gzip - + - name: Upload win-x64 Release Asset uses: actions/upload-release-asset@v1.0.1 env: @@ -63,9 +66,9 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./release/win-x64-${{ env.VERSION }}.tar.gz - asset_name: win-x64-${{ env.VERSION }}-${{ env.VERSION }}.tar.gz + asset_name: win-x64-${{ env.VERSION }}-${{ env.VERSION_E }}.tar.gz asset_content_type: application/gzip - + - name: Upload linux-x64 Release Asset uses: actions/upload-release-asset@v1.0.1 env: @@ -73,9 +76,9 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./release/linux-x64-${{ env.VERSION }}.tar.gz - asset_name: linux-x64-${{ env.VERSION }}-${{ env.VERSION }}.tar.gz + asset_name: linux-x64-${{ env.VERSION }}-${{ env.VERSION_E }}.tar.gz asset_content_type: application/gzip - + - name: Upload osx-x64 Release Asset uses: actions/upload-release-asset@v1.0.1 env: @@ -83,5 +86,5 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./release/osx-x64-${{ env.VERSION }}.tar.gz - asset_name: osx-x64-${{ env.VERSION }}-${{ env.VERSION }}.tar.gz + asset_name: osx-x64-${{ env.VERSION }}-${{ env.VERSION_E }}.tar.gz asset_content_type: application/gzip \ No newline at end of file diff --git a/.version b/.version new file mode 100644 index 0000000..cd99d38 --- /dev/null +++ b/.version @@ -0,0 +1 @@ +1.14.0 \ No newline at end of file diff --git a/Arrowgene.Services.PingPong/Arrowgene.Services.PingPong.csproj b/Arrowgene.Services.PingPong/Arrowgene.Services.PingPong.csproj deleted file mode 100644 index 1a15946..0000000 --- a/Arrowgene.Services.PingPong/Arrowgene.Services.PingPong.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - netcoreapp3.0 - - - - - - - diff --git a/Arrowgene.Services.PingPong/Connection.cs b/Arrowgene.Services.PingPong/Connection.cs deleted file mode 100644 index 1371e95..0000000 --- a/Arrowgene.Services.PingPong/Connection.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp; - -namespace Arrowgene.Services.PingPong -{ - public class Connection - { - private readonly ILogger _logger; - - public Connection(ITcpSocket clientSocket) - { - _logger = LogProvider.Logger(this); - Socket = clientSocket; - } - - public string Identity => Socket.Identity; - public ITcpSocket Socket { get; } - - public List Receive(byte[] data) - { - List packets; - try - { - packets = new List(); - packets.Add(new Packet(data)); - } - catch (Exception ex) - { - _logger.Exception(ex); - packets = new List(); - } - - return packets; - } - - public void Send(byte[] data) - { - Socket.Send(data); - } - - public void Send(Packet packet) - { - Socket.Send(packet.Data); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services.PingPong/Handler/PingPongHandler.cs b/Arrowgene.Services.PingPong/Handler/PingPongHandler.cs deleted file mode 100644 index 2fa31d9..0000000 --- a/Arrowgene.Services.PingPong/Handler/PingPongHandler.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Arrowgene.Services.PingPong.Handler -{ - public class PingPongHandler : IHandler - { - public int Id => 0; - - public void Handle(Connection connection, Packet packet) - { - connection.Send(packet.Data); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services.PingPong/IHandler.cs b/Arrowgene.Services.PingPong/IHandler.cs deleted file mode 100644 index ea7197e..0000000 --- a/Arrowgene.Services.PingPong/IHandler.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Arrowgene.Services.PingPong -{ - public interface IHandler - { - int Id { get; } - void Handle(Connection connection, Packet packet); - } -} \ No newline at end of file diff --git a/Arrowgene.Services.PingPong/Packet.cs b/Arrowgene.Services.PingPong/Packet.cs deleted file mode 100644 index 7876fdc..0000000 --- a/Arrowgene.Services.PingPong/Packet.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Arrowgene.Services.PingPong -{ - public class Packet - { - public byte[] Data { get; set; } - public int Id { get; set; } - - public Packet(byte[] data) - { - Id = 0; - Data = data; - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services.PingPong/PingPongConsumer.cs b/Arrowgene.Services.PingPong/PingPongConsumer.cs deleted file mode 100644 index 7ed37f5..0000000 --- a/Arrowgene.Services.PingPong/PingPongConsumer.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp; -using Arrowgene.Services.Networking.Tcp.Consumer.BlockingQueueConsumption; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; - -namespace Arrowgene.Services.PingPong -{ - public class PingPongConsumer : ThreadedBlockingQueueConsumer - { - private readonly Dictionary _handlers; - private readonly Dictionary _connections; - private readonly object _lock; - private readonly ILogger _logger; - - public PingPongConsumer(AsyncEventSettings socketSetting, string identity = "PingPongConsumer") : base( - socketSetting, identity) - { - _logger = LogProvider.Logger(this); - _connections = new Dictionary(); - _handlers = new Dictionary(); - _lock = new object(); - } - - public void AddHandler(IHandler handler) - { - if (_handlers.ContainsKey(handler.Id)) - { - _logger.Error($"ClientHandlerId: {handler.Id} already exists"); - } - else - { - _handlers.Add(handler.Id, handler); - } - } - - protected override void HandleReceived(ITcpSocket socket, byte[] data) - { - if (!socket.IsAlive) - { - return; - } - - Connection connection; - lock (_lock) - { - if (!_connections.ContainsKey(socket)) - { - _logger.Error($"[{socket.Identity}] Client does not exist in lookup"); - return; - } - - connection = _connections[socket]; - } - - List packets = connection.Receive(data); - foreach (Packet packet in packets) - { - if (!_handlers.ContainsKey(packet.Id)) - { - _logger.Error($"[{socket.Identity}] Unknown Packet"); - return; - } - - IHandler handler = _handlers[packet.Id]; - try - { - handler.Handle(connection, packet); - } - catch (Exception ex) - { - _logger.Error($"[{connection.Identity}] Exception"); - _logger.Exception(ex); - } - } - } - - protected override void HandleDisconnected(ITcpSocket socket) - { - Connection connection; - lock (_lock) - { - if (!_connections.ContainsKey(socket)) - { - _logger.Error($"[{socket.Identity}] Disconnected client does not exist in lookup"); - return; - } - - connection = _connections[socket]; - _connections.Remove(socket); - _logger.Debug($"Clients Count: {_connections.Count}"); - } - - _logger.Info($"[{connection.Identity}] Client disconnected"); - } - - protected override void HandleConnected(ITcpSocket socket) - { - Connection connection = new Connection(socket); - lock (_lock) - { - _connections.Add(socket, connection); - _logger.Debug($"Clients Count: {_connections.Count}"); - } - - _logger.Info($"[{connection.Identity}] Client connected"); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services.PingPong/Program.cs b/Arrowgene.Services.PingPong/Program.cs deleted file mode 100644 index dbd8e0d..0000000 --- a/Arrowgene.Services.PingPong/Program.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Net; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; -using Arrowgene.Services.PingPong.Handler; - -namespace Arrowgene.Services.PingPong -{ - class Program - { - static void Main(string[] args) - { - int threads = 1; - int timeout = -1; - int connections = 100; - int buffer = 2000; - ushort port = 9999; - - foreach (string arg in args) - { - if (arg.StartsWith('-')) - { - string argument = arg.Substring(1); - string[] keyValue = argument.Split('='); - if (keyValue.Length != 2) - { - continue; - } - - string key = keyValue[0]; - string value = keyValue[1]; - - switch (key) - { - case "threads": - { - if (!int.TryParse(value, out threads)) - { - Console.WriteLine($"Invalid parameter for threads {value}"); - } - Console.WriteLine($"Threads={threads}"); - break; - } - case "timeout": - { - if (!int.TryParse(value, out timeout)) - { - Console.WriteLine($"Invalid parameter for timeout {value}"); - } - Console.WriteLine($"Timeout={timeout}"); - break; - } - case "connections": - { - if (!int.TryParse(value, out connections)) - { - Console.WriteLine($"Invalid parameter for connections {value}"); - } - Console.WriteLine($"Connections={connections}"); - break; - } - case "buffer": - { - if (!int.TryParse(value, out buffer)) - { - Console.WriteLine($"Invalid parameter for buffer {value}"); - } - Console.WriteLine($"Connections={buffer}"); - break; - } - case "port": - { - if (!ushort.TryParse(value, out port)) - { - Console.WriteLine($"Invalid parameter for port {value}"); - } - Console.WriteLine($"Port={port}"); - break; - } - } - } - } - - Console.WriteLine($"Threads: {threads}"); - Console.WriteLine($"Timeout: {timeout}"); - Console.WriteLine($"Connections: {connections}"); - Console.WriteLine($"Buffer: {buffer}"); - - LogProvider.GlobalLogWrite += LogProviderOnLogWrite; - - AsyncEventSettings settings = new AsyncEventSettings(); - settings.MaxUnitOfOrder = threads; - settings.SocketTimeoutSeconds = timeout; - settings.MaxConnections = connections; - settings.NumSimultaneouslyWriteOperations = connections; - settings.BufferSize = buffer; - - PingPongConsumer consumer = new PingPongConsumer(settings); - consumer.AddHandler(new PingPongHandler()); - AsyncEventServer server = new AsyncEventServer(IPAddress.Any, port, consumer, settings); - - server.Start(); - Console.WriteLine("Press any key to exit..."); - Console.ReadKey(); - server.Stop(); - } - - private static void LogProviderOnLogWrite(object sender, LogWriteEventArgs logWriteEventArgs) - { - Console.WriteLine(logWriteEventArgs.Log); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services.Playground/Demo/TcpConnectionDemo.cs b/Arrowgene.Services.Playground/Demo/TcpConnectionDemo.cs index 4aa4a48..0161624 100644 --- a/Arrowgene.Services.Playground/Demo/TcpConnectionDemo.cs +++ b/Arrowgene.Services.Playground/Demo/TcpConnectionDemo.cs @@ -1,10 +1,10 @@ using System; using System.Net; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp.Client; -using Arrowgene.Services.Networking.Tcp.Client.SyncReceive; -using Arrowgene.Services.Networking.Tcp.Consumer.EventConsumption; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; +using Arrowgene.Logging; +using Arrowgene.Networking.Tcp.Client; +using Arrowgene.Networking.Tcp.Client.SyncReceive; +using Arrowgene.Networking.Tcp.Consumer.EventConsumption; +using Arrowgene.Networking.Tcp.Server.AsyncEvent; namespace Arrowgene.Services.Playground.Demo { diff --git a/Arrowgene.Services.Playground/Demo/TcpEchoDemo.cs b/Arrowgene.Services.Playground/Demo/TcpEchoDemo.cs index cc35ff2..d01f866 100644 --- a/Arrowgene.Services.Playground/Demo/TcpEchoDemo.cs +++ b/Arrowgene.Services.Playground/Demo/TcpEchoDemo.cs @@ -1,11 +1,9 @@ using System; using System.Net; using System.Threading; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp.Consumer.BlockingQueueConsumption; -using Arrowgene.Services.Networking.Tcp.Server; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; - +using Arrowgene.Logging; +using Arrowgene.Networking.Tcp.Consumer.BlockingQueueConsumption; +using Arrowgene.Networking.Tcp.Server.AsyncEvent; namespace Arrowgene.Services.Playground.Demo { public class TcpEchoDemo diff --git a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/HandleLogin.cs b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/HandleLogin.cs index 9557c84..ac6f245 100644 --- a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/HandleLogin.cs +++ b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/HandleLogin.cs @@ -1,5 +1,5 @@ using System; -using Arrowgene.Services.Networking.Tcp; +using Arrowgene.Networking.Tcp; using Arrowgene.Services.Networking.Tcp.Consumer.Messages; using Arrowgene.Services.Playground.Demo.TcpMessageProtocol.Models; diff --git a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/MPClient.cs b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/MPClient.cs index 43576e9..6f040f2 100644 --- a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/MPClient.cs +++ b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Client/MPClient.cs @@ -1,6 +1,6 @@ using System; -using Arrowgene.Services.Networking.Tcp.Client; -using Arrowgene.Services.Networking.Tcp.Client.SyncReceive; +using Arrowgene.Networking.Tcp.Client; +using Arrowgene.Networking.Tcp.Client.SyncReceive; using Arrowgene.Services.Networking.Tcp.Consumer.Messages; namespace Arrowgene.Services.Playground.Demo.TcpMessageProtocol.Client diff --git a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/HandleLogin.cs b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/HandleLogin.cs index 7b14550..375cca8 100644 --- a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/HandleLogin.cs +++ b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/HandleLogin.cs @@ -1,4 +1,5 @@ using System; +using Arrowgene.Networking.Tcp; using Arrowgene.Services.Networking.Tcp; using Arrowgene.Services.Networking.Tcp.Consumer.Messages; using Arrowgene.Services.Playground.Demo.TcpMessageProtocol.Models; diff --git a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/MPServer.cs b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/MPServer.cs index f7cc02e..8542ad5 100644 --- a/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/MPServer.cs +++ b/Arrowgene.Services.Playground/Demo/TcpMessageProtocol/Server/MPServer.cs @@ -1,6 +1,6 @@ using System.Net; +using Arrowgene.Networking.Tcp.Server.AsyncEvent; using Arrowgene.Services.Networking.Tcp.Consumer.Messages; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; namespace Arrowgene.Services.Playground.Demo.TcpMessageProtocol.Server { diff --git a/Arrowgene.Services.Playground/Demo/UdpClientDemo.cs b/Arrowgene.Services.Playground/Demo/UdpClientDemo.cs index 503af4f..2644a03 100644 --- a/Arrowgene.Services.Playground/Demo/UdpClientDemo.cs +++ b/Arrowgene.Services.Playground/Demo/UdpClientDemo.cs @@ -1,7 +1,7 @@ using System; using System.Net; using System.Threading; -using Arrowgene.Services.Networking.Udp; +using Arrowgene.Networking.Udp; namespace Arrowgene.Services.Playground.Demo { diff --git a/Arrowgene.Services.Playground/Demo/UdpServerDemo.cs b/Arrowgene.Services.Playground/Demo/UdpServerDemo.cs index 68048cd..24dfefd 100644 --- a/Arrowgene.Services.Playground/Demo/UdpServerDemo.cs +++ b/Arrowgene.Services.Playground/Demo/UdpServerDemo.cs @@ -1,7 +1,7 @@ using System; using System.Net; using System.Threading; -using Arrowgene.Services.Networking.Udp; +using Arrowgene.Networking.Udp; namespace Arrowgene.Services.Playground.Demo { diff --git a/Arrowgene.Services.Playground/Program.cs b/Arrowgene.Services.Playground/Program.cs index 9ac9658..9cadf44 100644 --- a/Arrowgene.Services.Playground/Program.cs +++ b/Arrowgene.Services.Playground/Program.cs @@ -1,5 +1,4 @@ using Arrowgene.Services.Playground.Demo; -using Arrowgene.Services.Playground.Demo.TcpMessageProtocol; namespace Arrowgene.Services.Playground { diff --git a/Arrowgene.Services.sln b/Arrowgene.Services.sln index fec86df..3f95599 100755 --- a/Arrowgene.Services.sln +++ b/Arrowgene.Services.sln @@ -1,14 +1,12 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29613.14 MinimumVisualStudioVersion = 15.0.26124.0 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Arrowgene.Services", "Arrowgene.Services\Arrowgene.Services.csproj", "{5ECAC55A-187D-4834-993A-EB261E78DF3A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Arrowgene.Services.Playground", "Arrowgene.Services.Playground\Arrowgene.Services.Playground.csproj", "{A776E123-26B6-4444-88B7-3077911CB8EB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Arrowgene.Services.PingPong", "Arrowgene.Services.PingPong\Arrowgene.Services.PingPong.csproj", "{BF84327A-9092-43F2-89B2-32AFD30EF38D}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -18,9 +16,6 @@ Global Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5ECAC55A-187D-4834-993A-EB261E78DF3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5ECAC55A-187D-4834-993A-EB261E78DF3A}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -46,17 +41,11 @@ Global {A776E123-26B6-4444-88B7-3077911CB8EB}.Release|x64.Build.0 = Release|x64 {A776E123-26B6-4444-88B7-3077911CB8EB}.Release|x86.ActiveCfg = Release|x86 {A776E123-26B6-4444-88B7-3077911CB8EB}.Release|x86.Build.0 = Release|x86 - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Debug|x64.ActiveCfg = Debug|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Debug|x64.Build.0 = Debug|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Debug|x86.ActiveCfg = Debug|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Debug|x86.Build.0 = Debug|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Release|Any CPU.Build.0 = Release|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Release|x64.ActiveCfg = Release|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Release|x64.Build.0 = Release|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Release|x86.ActiveCfg = Release|Any CPU - {BF84327A-9092-43F2-89B2-32AFD30EF38D}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FEEE965A-941F-47A9-BD98-DF5835890B98} EndGlobalSection EndGlobal diff --git a/Arrowgene.Services/Arrowgene.Services.asmdef b/Arrowgene.Services/Arrowgene.Services.asmdef deleted file mode 100644 index 52b5cba..0000000 --- a/Arrowgene.Services/Arrowgene.Services.asmdef +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "Arrowgene.Services", - "references": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [] -} \ No newline at end of file diff --git a/Arrowgene.Services/Arrowgene.Services.csproj b/Arrowgene.Services/Arrowgene.Services.csproj index 8051931..9537e02 100755 --- a/Arrowgene.Services/Arrowgene.Services.csproj +++ b/Arrowgene.Services/Arrowgene.Services.csproj @@ -3,13 +3,18 @@ netstandard2.1 Arrowgene.Services Arrowgene - Copyright © 2017 Arrowgene + Copyright © 2017-2020 Arrowgene $(Version) sebastian-heinz - Arrowgene.Services aids in creating a server with multiple clients. + Arrowgene.Services network sockets and data manipulation https://github.com/sebastian-heinz/Arrowgene.Services https://github.com/sebastian-heinz/Arrowgene.Services git - game,server,client,socket,network + server,client,socket,network,arrowgene + + + + + \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/Buffer.cs b/Arrowgene.Services/Buffers/Buffer.cs deleted file mode 100644 index 944e297..0000000 --- a/Arrowgene.Services/Buffers/Buffer.cs +++ /dev/null @@ -1,601 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Collections.Generic; -using System.Text; - -namespace Arrowgene.Services.Buffers -{ - public abstract class Buffer : IBuffer, IBufferProvider, ICloneable - { - public static string NoEncoding(byte[] bytes) - { - string s = string.Empty; - foreach (byte b in bytes) - { - s += (char) b; - } - - return s; - } - - public static byte[] NoEncoding(string str) - { - List bytes = new List(); - foreach (char c in str) - { - bytes.Add((byte) c); - } - - return bytes.ToArray(); - } - - private readonly IEndiannessSwapper _endiannessSwapper; - - public Buffer() - { - _endiannessSwapper = - new EndiannessSwapper(BitConverter.IsLittleEndian ? Endianness.Little : Endianness.Big); - } - - public Buffer(IEndiannessSwapper endiannessSwapper) - { - _endiannessSwapper = endiannessSwapper; - } - - public Endianness Endianness => _endiannessSwapper.Endianness; - public abstract int Size { get; } - public abstract int Position { get; set; } - public abstract void SetSize(int size); - public abstract void SetPositionStart(); - public abstract void SetPositionEnd(); - public abstract IBuffer Clone(int offset, int length); - public abstract IBuffer Provide(); - public abstract IBuffer Provide(byte[] buffer); - public abstract byte[] GetAllBytes(); - public abstract byte[] GetAllBytes(int offset); - public abstract void WriteByte(byte value); - public abstract void WriteBytes(byte[] bytes); - public abstract void WriteBytes(byte[] source, int srcOffset, int length); - public abstract void WriteBytes(byte[] source, int srcOffset, int dstOffset, int count); - public abstract void WriteDecimal(decimal value); - public abstract byte ReadByte(); - public abstract byte GetByte(int offset); - public abstract byte[] ReadBytes(int length); - public abstract byte[] GetBytes(int offset, int length); - public abstract decimal GetDecimal(int offset); - public abstract decimal ReadDecimal(); - public abstract void WriteInt16_Implementation(short value); - public abstract void WriteUInt16_Implementation(ushort value); - public abstract void WriteInt32_Implementation(int value); - public abstract void WriteUInt32_Implementation(uint value); - public abstract void WriteInt64_Implementation(long value); - public abstract void WriteUInt64_Implementation(ulong value); - public abstract void WriteFloat_Implementation(float value); - public abstract void WriteDouble_Implementation(double value); - public abstract short GetInt16_Implementation(int offset); - public abstract ushort GetUInt16_Implementation(int offset); - public abstract short ReadInt16_Implementation(); - public abstract ushort ReadUInt16_Implementation(); - public abstract int GetInt32_Implementation(int offset); - public abstract uint GetUInt32_Implementation(int offset); - public abstract int ReadInt32_Implementation(); - public abstract uint ReadUInt32_Implementation(); - public abstract long GetInt64_Implementation(int offset); - public abstract ulong GetUInt64_Implementation(int offset); - public abstract long ReadInt64_Implementation(); - public abstract ulong ReadUInt64_Implementation(); - public abstract float GetFloat_Implementation(int offset); - public abstract float ReadFloat_Implementation(); - public abstract double GetDouble_Implementation(int offset); - public abstract double ReadDouble_Implementation(); - - public virtual void SetEndianness(Endianness endianness) - { - _endiannessSwapper.Endianness = endianness; - } - - public virtual void WriteInt16(short value) - { - _endiannessSwapper.WriteSwap(value, WriteInt16_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteUInt16(ushort value) - { - _endiannessSwapper.WriteSwap(value, WriteUInt16_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteInt32(int value) - { - _endiannessSwapper.WriteSwap(value, WriteInt32_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteUInt32(uint value) - { - _endiannessSwapper.WriteSwap(value, WriteUInt32_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteInt64(long value) - { - _endiannessSwapper.WriteSwap(value, WriteInt64_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteUInt64(ulong value) - { - _endiannessSwapper.WriteSwap(value, WriteUInt64_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteFloat(float value) - { - _endiannessSwapper.WriteSwap(value, WriteFloat_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual void WriteDouble(double value) - { - _endiannessSwapper.WriteSwap(value, WriteDouble_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual short GetInt16(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetInt16_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual ushort GetUInt16(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetUInt16_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual short ReadInt16() - { - return _endiannessSwapper.ReadSwap(ReadInt16_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual ushort ReadUInt16() - { - return _endiannessSwapper.ReadSwap(ReadUInt16_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual int GetInt32(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetInt32_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual uint GetUInt32(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetUInt32_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual int ReadInt32() - { - return _endiannessSwapper.ReadSwap(ReadInt32_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual uint ReadUInt32() - { - return _endiannessSwapper.ReadSwap(ReadUInt32_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual long GetInt64(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetInt64_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual ulong GetUInt64(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetUInt64_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual long ReadInt64() - { - return _endiannessSwapper.ReadSwap(ReadInt64_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual ulong ReadUInt64() - { - return _endiannessSwapper.ReadSwap(ReadUInt64_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual float GetFloat(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetFloat_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual float ReadFloat() - { - return _endiannessSwapper.ReadSwap(ReadFloat_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual double GetDouble(int offset) - { - return _endiannessSwapper.GetSwap(offset, GetDouble_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual double ReadDouble() - { - return _endiannessSwapper.ReadSwap(ReadDouble_Implementation, _endiannessSwapper.SwapBytes); - } - - public virtual short GetInt16(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetInt16, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual ushort GetUInt16(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetUInt16, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual short ReadInt16(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadInt16, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual ushort ReadUInt16(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadUInt16, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual int GetInt32(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetInt32, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual uint GetUInt32(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetUInt32, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual int ReadInt32(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadInt32, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual uint ReadUInt32(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadUInt32, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual long GetInt64(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetInt64, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual ulong GetUInt64(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetUInt64, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual long ReadInt64(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadInt64, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual ulong ReadUInt64(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadUInt64, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual float GetFloat(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetFloat, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual float ReadFloat(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadFloat, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual double GetDouble(int offset, Endianness endianness) - { - return _endiannessSwapper.GetSwap(offset, GetDouble, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual double ReadDouble(Endianness endianness) - { - return _endiannessSwapper.ReadSwap(ReadDouble, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteString(string value) - { - WriteString(value, NoEncoding); - } - - public virtual void WriteString(string value, Encoding encoding) - { - WriteString(value, encoding.GetBytes); - } - - public virtual void WriteString(string value, Func converter) - { - byte[] bytes = converter(value); - WriteBytes(bytes); - } - - public virtual void WriteFixedString(string value, int length, Func converter) - { - byte[] bytes = converter(value); - for (int i = 0; i < bytes.Length && i < length; i++) - { - WriteByte(bytes[i]); - } - - int diff = length - bytes.Length; - if (diff > 0) - { - WriteBytes(new byte[diff]); - } - } - - public virtual void WriteFixedString(string value, int length, Encoding encoding) - { - WriteFixedString(value, length, encoding.GetBytes); - } - - public virtual void WriteFixedString(string value, int length) - { - WriteFixedString(value, length, NoEncoding); - } - - public virtual void WriteCString(string value) - { - WriteString(value); - WriteByte(0); - } - - public virtual void WriteCString(string value, Encoding encoding) - { - WriteString(value, encoding); - WriteByte(0); - } - - public virtual void WriteCString(string value, Func converter) - { - WriteString(value, converter); - WriteByte(0); - } - - public virtual string ToHexString(string separator = null) - { - return Service.ToHexString(GetAllBytes(), separator); - } - - public virtual string ToAsciiString(string separator = " ") - { - return Service.ToAsciiString(GetAllBytes(), separator); - } - - public virtual string GetString(int offset, int length) - { - return GetString(offset, length, NoEncoding); - } - - public virtual string GetString(int offset, int length, Encoding encoding) - { - return GetString(offset, length, encoding.GetString); - } - - public virtual string GetString(int offset, int length, Func converter) - { - int position = Position; - Position = offset; - string value = ReadString(length, converter); - Position = position; - return value; - } - - public virtual string ReadString(int length) - { - return ReadString(length, NoEncoding); - } - - public virtual string ReadString(int length, Encoding encoding) - { - return ReadString(length, encoding.GetString); - } - - public virtual string ReadString(int length, Func converter) - { - byte[] bytes = ReadBytes(length); - return converter(bytes); - } - - public virtual string ReadFixedString(int length) - { - return ReadFixedString(length, NoEncoding); - } - - public virtual string ReadFixedString(int length, Encoding encoding) - { - return ReadFixedString(length, encoding.GetString); - } - - public virtual string ReadFixedString(int length, Func converter) - { - byte[] bytes = ReadBytesFixedZeroTerminated(length); - return converter(bytes); - } - - public virtual string GetCString(int offset) - { - return GetCString(offset, NoEncoding); - } - - public virtual string GetCString(int offset, Encoding encoding) - { - return GetCString(offset, encoding.GetString); - } - - public virtual string GetCString(int offset, Func converter) - { - int position = Position; - Position = offset; - string value = ReadCString(converter); - Position = position; - return value; - } - - public virtual byte[] ReadBytesZeroTerminated() - { - return ReadBytesTerminated(0); - } - - public virtual byte[] ReadBytesFixedZeroTerminated(int length) - { - return ReadBytesFixedTerminated(length, 0); - } - - public virtual byte[] ReadBytesTerminated(byte termination) - { - List readBytes = new List(); - while (Position < Size) - { - byte b = ReadByte(); - if (b != termination) - { - readBytes.Add(b); - } - else - { - break; - } - } - - return readBytes.ToArray(); - } - - public virtual byte[] ReadBytesFixedTerminated(int length, byte termination) - { - byte[] bytes = ReadBytes(length); - List readBytes = new List(); - foreach (byte b in bytes) - { - if (b != termination) - { - readBytes.Add(b); - } - else - { - break; - } - } - - return readBytes.ToArray(); - } - - public virtual string ReadCString() - { - return ReadCString(NoEncoding); - } - - public virtual string ReadCString(Encoding encoding) - { - return ReadCString(encoding.GetString); - } - - public virtual string ReadCString(Func converter) - { - byte[] bytes = ReadBytesZeroTerminated(); - return converter(bytes); - } - - public virtual void WriteBuffer(IBuffer value, int offset, int length) - { - WriteBytes(value.GetBytes(offset, length)); - } - - public virtual void WriteBuffer(IBuffer value) - { - WriteBytes(value.GetAllBytes()); - } - - public virtual IBuffer Clone(int length) - { - return Clone(0, length); - } - - public virtual IBuffer Clone() - { - return Clone(Size); - } - - public virtual void WriteInt16(short value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteInt16, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteInt32(int value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteInt32, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteInt64(long value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteInt64, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteUInt16(ushort value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteUInt16, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteUInt32(uint value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteUInt32, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteUInt64(ulong value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteUInt64, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteFloat(float value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteFloat, _endiannessSwapper.SwapBytes, endianness); - } - - public virtual void WriteDouble(double value, Endianness endianness) - { - _endiannessSwapper.WriteSwap(value, WriteDouble, _endiannessSwapper.SwapBytes, endianness); - } - - public string Dump() - { - return ToAsciiString() + - Environment.NewLine + - ToHexString(); - } - - public override string ToString() - { - return $"Size:{Size} Position:{Position}"; - } - - object ICloneable.Clone() - { - return Clone(); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/BufferManager.cs b/Arrowgene.Services/Buffers/BufferManager.cs deleted file mode 100644 index 72f9084..0000000 --- a/Arrowgene.Services/Buffers/BufferManager.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System.Collections.Generic; -using System.Net.Sockets; - -namespace Arrowgene.Services.Buffers -{ - - // TODO rework this one - public class BufferManager - { - private readonly int _numBytes; - private readonly int _bufferSize; - private readonly Stack _freeIndexPool; - - private int _currentIndex; - private byte[] _buffer; - - public BufferManager(int totalBytes, int bufferSize) - { - _numBytes = totalBytes; - _currentIndex = 0; - _bufferSize = bufferSize; - _freeIndexPool = new Stack(); - } - - public void InitBuffer() - { - _buffer = new byte[_numBytes]; - } - - public bool SetBuffer(SocketAsyncEventArgs args) - { - if (_freeIndexPool.Count > 0) - { - args.SetBuffer(_buffer, _freeIndexPool.Pop(), _bufferSize); - } - else - { - if (_numBytes - _bufferSize < _currentIndex) - { - return false; - } - - args.SetBuffer(_buffer, _currentIndex, _bufferSize); - _currentIndex += _bufferSize; - } - - return true; - } - - public void FreeBuffer(SocketAsyncEventArgs args) - { - _freeIndexPool.Push(args.Offset); - args.SetBuffer(null, 0, 0); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/Endianness.cs b/Arrowgene.Services/Buffers/Endianness.cs deleted file mode 100644 index 71bd45b..0000000 --- a/Arrowgene.Services/Buffers/Endianness.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Arrowgene.Services.Buffers -{ - public enum Endianness - { - Little, - Big - } - -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/EndiannessSwapper.cs b/Arrowgene.Services/Buffers/EndiannessSwapper.cs deleted file mode 100644 index d738149..0000000 --- a/Arrowgene.Services/Buffers/EndiannessSwapper.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System; - -namespace Arrowgene.Services.Buffers -{ - public class EndiannessSwapper : IEndiannessSwapper - { - public EndiannessSwapper(Endianness endianness) - { - Endianness = endianness; - } - - public Endianness Endianness { get; set; } - - public bool SwapNeeded(Endianness currentEndianness, Endianness targetEndianness) - { - return currentEndianness != targetEndianness; - } - - public ushort SwapBytes(ushort x) - { - return (ushort) ((x >> 8) | (x << 8)); - } - - public uint SwapBytes(uint x) - { - x = (x >> 16) | (x << 16); - return ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8); - } - - public ulong SwapBytes(ulong x) - { - x = (x >> 32) | (x << 32); - x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16); - return ((x & 0xFF00FF00FF00FF00) >> 8) | ((x & 0x00FF00FF00FF00FF) << 8); - } - - public float SwapBytes(float input) - { - byte[] tmpIn = BitConverter.GetBytes(input); - byte[] tmpOut = new byte[4]; - tmpOut[0] = tmpIn[3]; - tmpOut[1] = tmpIn[2]; - tmpOut[2] = tmpIn[1]; - tmpOut[3] = tmpIn[0]; - return BitConverter.ToSingle(tmpOut, 0); - } - - public double SwapBytes(double input) - { - byte[] tmpIn = BitConverter.GetBytes(input); - byte[] tmpOut = new byte[8]; - tmpOut[0] = tmpIn[7]; - tmpOut[1] = tmpIn[6]; - tmpOut[2] = tmpIn[5]; - tmpOut[3] = tmpIn[4]; - tmpOut[4] = tmpIn[3]; - tmpOut[5] = tmpIn[2]; - tmpOut[6] = tmpIn[1]; - tmpOut[7] = tmpIn[0]; - return BitConverter.ToSingle(tmpOut, 0); - } - - public short SwapBytes(short value) - { - return (short) SwapBytes((ushort) value); - } - - public int SwapBytes(int value) - { - return (int) SwapBytes((uint) value); - } - - public long SwapBytes(long value) - { - return (long) SwapBytes((ulong) value); - } - - public T GetSwap(int offset, Func getFunction, Func swapFunction, Endianness endianness) - { - T value = getFunction(offset); - if (SwapNeeded(Endianness, endianness)) - { - value = swapFunction(value); - } - - return value; - } - - public T ReadSwap(Func readFunction, Func swapFunction, Endianness endianness) - { - T value = readFunction(); - if (SwapNeeded(Endianness, endianness)) - { - value = swapFunction(value); - } - - return value; - } - - public void WriteSwap(T value, Action writeFunction, Func swapFunction, Endianness endianness) - { - if (SwapNeeded(Endianness, endianness)) - { - value = swapFunction(value); - } - - writeFunction(value); - } - - public T GetSwap(int offset, Func getFunction, Func swapFunction) - { - return GetSwap(offset, getFunction, swapFunction, Endianness); - } - - public T ReadSwap(Func readFunction, Func swapFunction) - { - return ReadSwap(readFunction, swapFunction, Endianness); - } - - public void WriteSwap(T value, Action writeFunction, Func swapFunction) - { - WriteSwap(value, writeFunction, swapFunction, Endianness); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/IBuffer.cs b/Arrowgene.Services/Buffers/IBuffer.cs deleted file mode 100644 index 964a888..0000000 --- a/Arrowgene.Services/Buffers/IBuffer.cs +++ /dev/null @@ -1,472 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Text; - -namespace Arrowgene.Services.Buffers -{ - public interface IBuffer - { - /// - /// Gets the endianness for all operation without explicit endianness. - /// - Endianness Endianness { get; } - - /// - /// The current buffer size. - /// - int Size { get; } - - /// - /// Gets or Sets the cursor position. - /// - int Position { get; set; } - - /// - /// Sets the data size. - /// - void SetSize(int size); - - /// - /// Sets the default endianness to use for all operations - /// - void SetEndianness(Endianness endianness); - - /// - /// Set the cursor to the beginning of the buffer. - /// - void SetPositionStart(); - - /// - /// Set the cursor to the end of the buffer. - /// - void SetPositionEnd(); - - /// - /// Clone this buffer from an offset till the specified length. - /// - IBuffer Clone(int offset, int length); - - /// - /// Clone this buffer from start till the specified length. - /// - IBuffer Clone(int length); - - /// - /// Clone this buffer from start till the specified length. - /// - IBuffer Clone(); - - /// - /// Returns all written bytes without affecting the position. - /// - byte[] GetAllBytes(); - - /// - /// Returns all written bytes from a specific offset, without affecting the position. - /// - byte[] GetAllBytes(int offset); - - void WriteByte(byte value); - - void WriteBytes(byte[] bytes); - - void WriteBytes(byte[] bytes, int srcOffset, int count); - - void WriteBytes(byte[] bytes, int srcOffset, int dstOffset, int count); - - void WriteInt16(short value); - - void WriteUInt16(ushort value); - - void WriteInt16(short value, Endianness endianness); - - void WriteUInt16(ushort value, Endianness endianness); - - void WriteInt32(int value); - - void WriteUInt32(uint value); - - void WriteInt32(int value, Endianness endianness); - - void WriteUInt32(uint value, Endianness endianness); - - void WriteInt64(long value); - - void WriteUInt64(ulong value); - - void WriteInt64(long value, Endianness endianness); - - void WriteUInt64(ulong value, Endianness endianness); - - void WriteFloat(float value); - - void WriteFloat(float value, Endianness endianness); - - void WriteDouble(double value); - - void WriteDouble(double value, Endianness endianness); - - void WriteDecimal(decimal value); - - void WriteBuffer(IBuffer value); - - void WriteBuffer(IBuffer value, int offset, int length); - - /// - /// Read byte. - /// Advances the cursor. - /// - byte ReadByte(); - - /// - /// Get byte at specified offset. - /// Doesn't advance the cursor. - /// - byte GetByte(int offset); - - /// - /// Read bytes. - /// Advances the cursor. - /// - byte[] ReadBytes(int length); - - /// - /// Read bytes until end of stream or 0-byte. - /// Advances the cursor. - /// - byte[] ReadBytesZeroTerminated(); - - /// - /// Read bytes until 0-byte or length is reached. - /// Advances the cursor. - /// - byte[] ReadBytesFixedZeroTerminated(int length); - - /// - /// Read bytes until provided termination byte or length is reached. - /// Advances the cursor. - /// - byte[] ReadBytesFixedTerminated(int length, byte termination); - - /// - /// Read bytes until provided termination byte. - /// Advances the cursor. - /// - byte[] ReadBytesTerminated(byte termination); - - /// - /// Get bytes at specified offset. - /// Doesn't advance the cursor. - /// - byte[] GetBytes(int offset, int length); - - /// - /// Get Int16 at specified offset. - /// Doesn't advance the cursor. - /// - short GetInt16(int offset); - - short GetInt16(int offset, Endianness endianness); - - /// - /// Get UInt16 at specified offset. - /// Doesn't advance the cursor. - /// - ushort GetUInt16(int offset); - - ushort GetUInt16(int offset, Endianness endianness); - - /// - /// Read Int16. - /// Advances the cursor. - /// - short ReadInt16(); - - short ReadInt16(Endianness endianness); - - /// - /// Read UInt16. - /// Advances the cursor. - /// - ushort ReadUInt16(); - - ushort ReadUInt16(Endianness endianness); - - /// - /// Get Int32 at specified offset. - /// Doesn't advance the cursor. - /// - int GetInt32(int offset); - - int GetInt32(int offset, Endianness endianness); - - /// - /// Get UInt32 at specified offset. - /// Doesn't advance the cursor. - /// - uint GetUInt32(int offset); - - uint GetUInt32(int offset, Endianness endianness); - - /// - /// Read Int32. - /// Doesn't advance the cursor. - /// - int ReadInt32(); - - int ReadInt32(Endianness endianness); - - /// - /// Read UInt32. - /// Doesn't advance the cursor. - /// - uint ReadUInt32(); - - uint ReadUInt32(Endianness endianness); - - /// - /// Get Int64 at specified offset. - /// Doesn't advance the cursor. - /// - long GetInt64(int offset); - - long GetInt64(int offset, Endianness endianness); - - /// - /// Get UInt64 at specified offset. - /// Doesn't advance the cursor. - /// - ulong GetUInt64(int offset); - - ulong GetUInt64(int offset, Endianness endianness); - - /// - /// Read Int64. - /// Doesn't advance the cursor. - /// - long ReadInt64(); - - long ReadInt64(Endianness endianness); - - /// - /// Read UInt64. - /// Doesn't advance the cursor. - /// - ulong ReadUInt64(); - - ulong ReadUInt64(Endianness endianness); - - /// - /// Get Float at specified offset. - /// Doesn't advance the cursor. - /// - float GetFloat(int offset); - - float GetFloat(int offset, Endianness endianness); - - /// - /// Read Float - /// Doesn't advance the cursor. - /// - float ReadFloat(); - - float ReadFloat(Endianness endianness); - - /// - /// Get Double at specified offset. - /// Doesn't advance the cursor. - /// - double GetDouble(int offset); - - double GetDouble(int offset, Endianness endianness); - - /// - /// Read Double - /// Doesn't advance the cursor. - /// - double ReadDouble(); - - double ReadDouble(Endianness endianness); - - /// - /// Get Decimal at specified offset. - /// Doesn't advance the cursor. - /// - decimal GetDecimal(int offset); - - /// - /// Read Decimal - /// Doesn't advance the cursor. - /// - decimal ReadDecimal(); - - /// - /// Get a String at specified offset with a specific length. - /// Doesn't advance the cursor. - /// - string GetString(int offset, int length); - - /// - /// Get a String at specified offset with a specific length. - /// Doesn't advance the cursor. - /// - string GetString(int offset, int length, Encoding encoding); - - /// - /// Get a String at specified offset with a specific length. - /// Doesn't advance the cursor. - /// - string GetString(int offset, int length, Func converter); - - /// - /// Read a String with a specific length. - /// Advances the cursor. - /// - string ReadString(int length); - - /// - /// Read a String with a specific length. - /// Advances the cursor. - /// - string ReadString(int length, Encoding encoding); - - /// - /// Read a String with a specific length. - /// Advances the cursor. - /// - string ReadString(int length, Func converter); - - /// - /// Writes a string. - /// - void WriteString(string value); - - /// - /// Writes a string. - /// - void WriteString(string value, Encoding encoding); - - /// - /// Writes a string. - /// - void WriteString(string value, Func converter); - - /// - /// Reads a till a 0byte, but advances the position for the length. - /// - string ReadFixedString(int length); - - /// - /// Reads a till a 0byte, but advances the position for the length. - /// - string ReadFixedString(int length, Encoding encoding); - - /// - /// Reads a till a 0byte, but advances the position for the length. - /// - string ReadFixedString(int length, Func converter); - - /// - /// Writes a string and fills the remaining length with 0-bytes. - /// - void WriteFixedString(string value, int length); - - /// - /// Writes a string and fills the remaining length with 0-bytes. - /// - void WriteFixedString(string value, int length, Encoding encoding); - - /// - /// Writes a string and fills the remaining length with 0-bytes. - /// - void WriteFixedString(string value, int length, Func converter); - - /// - /// Read till a 0byte. - /// Advances the cursor. - /// - string ReadCString(); - - /// - /// Read till a 0byte. - /// Advances the cursor. - /// - string ReadCString(Encoding encoding); - - /// - /// Read till a 0byte. - /// Advances the cursor. - /// - string ReadCString(Func converter); - - /// - /// Read till a 0byte starting from a specified offset. - /// Doesn't advance the cursor. - /// - string GetCString(int offset); - - /// - /// Read till a 0byte starting from a specified offset. - /// Doesn't advance the cursor. - /// - string GetCString(int offset, Encoding encoding); - - /// - /// Read till a 0byte starting from a specified offset. - /// Doesn't advance the cursor. - /// - string GetCString(int offset, Func converter); - - /// - /// Write a null-terminated-string. - /// Advances the cursor. - /// - void WriteCString(string value); - - /// - /// Write a null-terminated-string. - /// Advances the cursor. - /// - void WriteCString(string value, Encoding encoding); - - /// - /// Write a null-terminated-string. - /// Advances the cursor. - /// - void WriteCString(string value, Func converter); - - /// - /// Hex representation of the buffer. - /// - string ToHexString(string? separator = null); - - /// - /// Ascii representation of the buffer. - /// - string ToAsciiString(string? separator = null); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/IBufferProvider.cs b/Arrowgene.Services/Buffers/IBufferProvider.cs deleted file mode 100644 index 8451b9a..0000000 --- a/Arrowgene.Services/Buffers/IBufferProvider.cs +++ /dev/null @@ -1,33 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -namespace Arrowgene.Services.Buffers -{ - public interface IBufferProvider - { - IBuffer Provide(); - IBuffer Provide(byte[] buffer); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/IEndianessSwapper.cs b/Arrowgene.Services/Buffers/IEndianessSwapper.cs deleted file mode 100644 index dcd3364..0000000 --- a/Arrowgene.Services/Buffers/IEndianessSwapper.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace Arrowgene.Services.Buffers -{ - public interface IEndiannessSwapper - { - Endianness Endianness { get; set; } - bool SwapNeeded(Endianness currentEndianness, Endianness targetEndianness); - ushort SwapBytes(ushort x); - uint SwapBytes(uint x); - ulong SwapBytes(ulong x); - float SwapBytes(float input); - double SwapBytes(double input); - short SwapBytes(short value); - int SwapBytes(int value); - long SwapBytes(long value); - T GetSwap(int offset, Func getFunction, Func swapFunction, Endianness endianness); - T ReadSwap(Func readFunction, Func swapFunction, Endianness endianness); - void WriteSwap(T value, Action writeFunction, Func swapFunction, Endianness endianness); - T GetSwap(int offset, Func getFunction, Func swapFunction); - T ReadSwap(Func readFunction, Func swapFunction); - void WriteSwap(T value, Action writeFunction, Func swapFunction); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Buffers/StreamBuffer.cs b/Arrowgene.Services/Buffers/StreamBuffer.cs deleted file mode 100644 index 0049f12..0000000 --- a/Arrowgene.Services/Buffers/StreamBuffer.cs +++ /dev/null @@ -1,333 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System.IO; - -namespace Arrowgene.Services.Buffers -{ - public class StreamBuffer : Buffer - { - private readonly MemoryStream _memoryStream; - private readonly BinaryWriter _binaryWriter; - private readonly BinaryReader _binaryReader; - - public StreamBuffer() - { - _memoryStream = new MemoryStream(); - _binaryReader = new BinaryReader(_memoryStream); - _binaryWriter = new BinaryWriter(_memoryStream); - } - - public StreamBuffer(byte[] buffer) : this() - { - _binaryWriter.Write(buffer); - } - - public StreamBuffer(byte[] buffer, int index, int count) : this() - { - _binaryWriter.Write(buffer, index, count); - } - - public StreamBuffer(string filePath) : this() - { - const int bufferSize = 1024; - byte[] buffer = new byte[bufferSize]; - using FileStream fileStream = File.OpenRead(filePath); - int read; - while ((read = fileStream.Read(buffer, 0, bufferSize)) > 0) - { - _binaryWriter.Write(buffer, 0, read); - } - } - - public override int Size => (int) _memoryStream.Length; - - public override int Position - { - get => (int) _memoryStream.Position; - set => _memoryStream.Position = value; - } - - public override void SetSize(int size) - { - _memoryStream.SetLength(size); - } - - public sealed override void SetPositionStart() - { - Position = 0; - } - - public override void SetPositionEnd() - { - Position = Size; - } - - public override IBuffer Clone(int offset, int length) - { - return new StreamBuffer(GetBytes(offset, length)); - } - - public override IBuffer Provide() - { - return new StreamBuffer(); - } - - public override IBuffer Provide(byte[] buffer) - { - return new StreamBuffer(buffer); - } - - public override byte[] GetAllBytes() - { - return GetAllBytes(0); - } - - public override byte[] GetAllBytes(int offset) - { - return GetBytes(offset, Size - offset); - } - - public override void WriteBytes(byte[] bytes) - { - _binaryWriter.Write(bytes); - } - - public override void WriteBytes(byte[] source, int srcOffset, int length) - { - _memoryStream.Write(source, srcOffset, length); - } - - public override void WriteBytes(byte[] source, int srcOffset, int dstOffset, int count) - { - _memoryStream.Position = dstOffset; - _memoryStream.Write(source, srcOffset, count); - } - - public override void WriteByte(byte value) - { - _binaryWriter.Write(value); - } - - public override void WriteInt16_Implementation(short value) - { - _binaryWriter.Write(value); - } - - public override void WriteUInt16_Implementation(ushort value) - { - _binaryWriter.Write(value); - } - - public override void WriteInt32_Implementation(int value) - { - _binaryWriter.Write(value); - } - - public override void WriteUInt32_Implementation(uint value) - { - _binaryWriter.Write(value); - } - - public override void WriteInt64_Implementation(long value) - { - _binaryWriter.Write(value); - } - - public override void WriteUInt64_Implementation(ulong value) - { - _binaryWriter.Write(value); - } - - public override void WriteFloat_Implementation(float value) - { - _binaryWriter.Write(value); - } - - public override void WriteDouble_Implementation(double value) - { - _binaryWriter.Write(value); - } - - public override void WriteDecimal(decimal value) - { - _binaryWriter.Write(value); - } - - public override byte ReadByte() - { - return _binaryReader.ReadByte(); - } - - public override byte GetByte(int offset) - { - int position = Position; - Position = offset; - byte b = ReadByte(); - Position = position; - return b; - } - - public override byte[] ReadBytes(int length) - { - return _binaryReader.ReadBytes(length); - } - - public override byte[] GetBytes(int offset, int length) - { - int position = Position; - Position = offset; - byte[] bytes = ReadBytes(length); - Position = position; - return bytes; - } - - public override short GetInt16_Implementation(int offset) - { - int position = Position; - Position = offset; - short value = ReadInt16(); - Position = position; - return value; - } - - public override ushort GetUInt16_Implementation(int offset) - { - int position = Position; - Position = offset; - ushort value = ReadUInt16(); - Position = position; - return value; - } - - public override short ReadInt16_Implementation() - { - return _binaryReader.ReadInt16(); - } - - public override ushort ReadUInt16_Implementation() - { - return _binaryReader.ReadUInt16(); - } - - public override int GetInt32_Implementation(int offset) - { - int position = Position; - Position = offset; - int value = ReadInt32(); - Position = position; - return value; - } - - public override uint GetUInt32_Implementation(int offset) - { - int position = Position; - Position = offset; - uint value = ReadUInt32(); - Position = position; - return value; - } - - public override int ReadInt32_Implementation() - { - return _binaryReader.ReadInt32(); - } - - public override uint ReadUInt32_Implementation() - { - return _binaryReader.ReadUInt32(); - } - - public override long GetInt64_Implementation(int offset) - { - int position = Position; - Position = offset; - long value = ReadInt64(); - Position = position; - return value; - } - - public override ulong GetUInt64_Implementation(int offset) - { - int position = Position; - Position = offset; - ulong value = ReadUInt64(); - Position = position; - return value; - } - - public override long ReadInt64_Implementation() - { - return _binaryReader.ReadInt64(); - } - - public override ulong ReadUInt64_Implementation() - { - return _binaryReader.ReadUInt64(); - } - - public override float GetFloat_Implementation(int offset) - { - int position = Position; - Position = offset; - float value = ReadFloat(); - Position = position; - return value; - } - - public override float ReadFloat_Implementation() - { - return _binaryReader.ReadSingle(); - } - - public override double GetDouble_Implementation(int offset) - { - int position = Position; - Position = offset; - double value = ReadDouble(); - Position = position; - return value; - } - - public override double ReadDouble_Implementation() - { - return _binaryReader.ReadDouble(); - } - - public override decimal GetDecimal(int offset) - { - int position = Position; - Position = offset; - decimal value = ReadDecimal(); - Position = position; - return value; - } - - public override decimal ReadDecimal() - { - return _binaryReader.ReadDecimal(); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Database/SqlScriptRunner.cs b/Arrowgene.Services/Database/SqlScriptRunner.cs index e06ed2b..33c0e89 100644 --- a/Arrowgene.Services/Database/SqlScriptRunner.cs +++ b/Arrowgene.Services/Database/SqlScriptRunner.cs @@ -1,7 +1,7 @@ using System; using System.IO; using System.Text; -using Arrowgene.Services.Logging; +using Arrowgene.Logging; namespace Arrowgene.Services.Database { diff --git a/Arrowgene.Services/Logging/ILogger.cs b/Arrowgene.Services/Logging/ILogger.cs deleted file mode 100644 index 151956d..0000000 --- a/Arrowgene.Services/Logging/ILogger.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace Arrowgene.Services.Logging -{ - public interface ILogger - { - event EventHandler LogWrite; - void Initialize(string identity, string name, object configuration); - void Write(LogLevel logLevel, string message, object tag); - void Trace(string message); - void Info(string message); - void Debug(string message); - void Error(string message); - void Exception(Exception exception); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Logging/Log.cs b/Arrowgene.Services/Logging/Log.cs deleted file mode 100644 index 7d931a2..0000000 --- a/Arrowgene.Services/Logging/Log.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; - -namespace Arrowgene.Services.Logging -{ - public class Log - { - public Log(LogLevel logLevel, string text, object tag = null, string loggerIdentity = null, string loggerName = null) - { - Text = text; - LogLevel = logLevel; - DateTime = DateTime.Now; - LoggerIdentity = loggerIdentity; - LoggerName = loggerName ?? ""; - Tag = tag; - } - - public string LoggerIdentity { get; } - - public string LoggerName { get; } - - public string Text { get; } - - public LogLevel LogLevel { get; } - - public DateTime DateTime { get; } - - public object Tag { get; } - - public T GetTag() - { - return Tag is T ? (T) Tag : default(T); - } - - public override string ToString() - { - string log = "{0:yyyy-MM-dd HH:mm:ss} - {1}"; - if (string.IsNullOrEmpty(LoggerName)) - { - log += "{2}:"; - } - else - { - log += " - {2}:"; - } - log += " {3}"; - return string.Format(log, DateTime, LogLevel, LoggerName, Text); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Logging/LogLevel.cs b/Arrowgene.Services/Logging/LogLevel.cs deleted file mode 100644 index 3b057ac..0000000 --- a/Arrowgene.Services/Logging/LogLevel.cs +++ /dev/null @@ -1,34 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -namespace Arrowgene.Services.Logging -{ - public enum LogLevel - { - Trace = 5, - Debug = 10, - Info = 20, - Error = 30 - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Logging/LogProvider.cs b/Arrowgene.Services/Logging/LogProvider.cs deleted file mode 100644 index 3ef5e08..0000000 --- a/Arrowgene.Services/Logging/LogProvider.cs +++ /dev/null @@ -1,187 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Collections.Generic; - -namespace Arrowgene.Services.Logging -{ - public sealed class LogProvider - { - private static readonly LogProvider _instance = new LogProvider(); - - static LogProvider() - { - } - - public static LogProvider Instance => _instance; - - public static ILogger Logger(object instance) - { - return Instance.GetLogger(instance); - } - - public static ILogger Logger(Type type) - { - return Instance.GetLogger(type); - } - - public static T Logger(object instance) where T : ILogger, new() - { - return Instance.GetLogger(instance); - } - - public static T Logger(Type type) where T : ILogger, new() - { - return Instance.GetLogger(type); - } - - public static T Logger(string identity, string zone = null) where T : ILogger, new() - { - return Instance.GetLogger(identity, zone); - } - - public static void Configure(object configuration) where T : ILogger, new() - { - Instance.SetConfigure(typeof(T), configuration); - } - - public static void Configure(Type type, object configuration) - { - Instance.SetConfigure(type.FullName, configuration); - } - - /// - /// Provide a configuration object that will be passed to every instance - /// by calling on it. - /// - public static void Configure(string identity, object configuration) - { - Instance.SetConfigure(identity, configuration); - } - - private readonly Dictionary _loggers; - private readonly Dictionary _configurations; - private readonly object _lock; - - private LogProvider() - { - _loggers = new Dictionary(); - _configurations = new Dictionary(); - _lock = new object(); - } - - /// - /// Notifies about any logging event from every ILogger instance - /// - public static event EventHandler GlobalLogWrite; - - public void SetConfigure(object configuration) where T : ILogger, new() - { - SetConfigure(typeof(T), configuration); - } - - public void SetConfigure(Type type, object configuration) - { - SetConfigure(type.FullName, configuration); - } - - /// - /// Provide a configuration object that will be passed to every instance - /// by calling on it. - /// - public void SetConfigure(string identity, object configuration) - { - _configurations.Add(identity, configuration); - } - - public ILogger GetLogger(object instance) - { - return GetLogger(instance); - } - - public ILogger GetLogger(Type type) - { - return GetLogger(type); - } - - public T GetLogger(object instance) where T : ILogger, new() - { - return GetLogger(instance.GetType()); - } - - public T GetLogger(Type type) where T : ILogger, new() - { - return GetLogger(type.FullName, type.Name); - } - - /// - /// Returns a logger that matches the identity or creates a new one. - /// - /// Unique token to identify a logger - /// Name to identify the log origin - /// Type of the logger instance - /// New instance of T or existing ILogger if the identity already exists - /// identity does not match T. - public T GetLogger(string identity, string name = null) where T : ILogger, new() - { - ILogger logger; - lock (_lock) - { - if (!_loggers.TryGetValue(identity, out logger)) - { - object configuration = null; - string typeName = typeof(T).FullName; - if (typeName != null && _configurations.ContainsKey(typeName)) - { - configuration = _configurations[typeName]; - } - - logger = new T(); - logger.Initialize(identity, name, configuration); - logger.LogWrite += LoggerOnLogWrite; - _loggers.Add(identity, logger); - } - } - - if (logger is T concreteLogger) - { - return concreteLogger; - } - - string realType = logger == null ? "null" : logger.GetType().ToString(); - throw new Exception($"Logger identity: {identity} is not type of {typeof(T)} but {realType}"); - } - - private void LoggerOnLogWrite(object sender, LogWriteEventArgs writeEventArgs) - { - EventHandler globalLogWrite = GlobalLogWrite; - if (globalLogWrite != null) - { - globalLogWrite(sender, writeEventArgs); - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Logging/LogWriteEventArgs.cs b/Arrowgene.Services/Logging/LogWriteEventArgs.cs deleted file mode 100644 index 109f67e..0000000 --- a/Arrowgene.Services/Logging/LogWriteEventArgs.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; - -namespace Arrowgene.Services.Logging -{ - public class LogWriteEventArgs : EventArgs - { - public LogWriteEventArgs(Log log) - { - Log = log; - } - - public Log Log { get; } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Logging/Logger.cs b/Arrowgene.Services/Logging/Logger.cs deleted file mode 100644 index b2979ae..0000000 --- a/Arrowgene.Services/Logging/Logger.cs +++ /dev/null @@ -1,98 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -using System; - -namespace Arrowgene.Services.Logging -{ - public class Logger : ILogger - { - private string _zone; - private string _identity; - - public Logger() - { - } - - public event EventHandler LogWrite; - - public virtual void Initialize(string identity, string zone, object configuration) - { - _identity = identity; - _zone = zone; - } - - public void Write(Log log) - { - OnLogWrite(log); - } - - public void Write(LogLevel logLevel, string message, object tag) - { - Log log = new Log(logLevel, message, tag, _identity, _zone); - Write(log); - } - - public void Trace(string message) - { - Write(LogLevel.Trace, message, null); - } - - public void Info(string message) - { - Write(LogLevel.Info, message, null); - } - - public void Debug(string message) - { - Write(LogLevel.Debug, message, null); - } - - public void Error(string message) - { - Write(LogLevel.Error, message, null); - } - - public void Exception(Exception exception) - { - if (exception == null) - { - Write(LogLevel.Error, "Exception was null.", null); - return; - } - - Write(LogLevel.Error, exception.ToString(), exception); - } - - private void OnLogWrite(Log log) - { - EventHandler logWrite = LogWrite; - if (logWrite != null) - { - LogWriteEventArgs logWriteEventArgs = new LogWriteEventArgs(log); - logWrite(this, logWriteEventArgs); - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Middleware/Middleware.cs b/Arrowgene.Services/Middleware/Middleware.cs index e9c699f..0b8a1bb 100644 --- a/Arrowgene.Services/Middleware/Middleware.cs +++ b/Arrowgene.Services/Middleware/Middleware.cs @@ -1,4 +1,4 @@ -using Arrowgene.Services.Logging; +using Arrowgene.Logging; namespace Arrowgene.Services.Middleware { diff --git a/Arrowgene.Services/Networking/NetworkPoint.cs b/Arrowgene.Services/Networking/NetworkPoint.cs deleted file mode 100644 index e9eb976..0000000 --- a/Arrowgene.Services/Networking/NetworkPoint.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Net; -using System.Runtime.Serialization; - -namespace Arrowgene.Services.Networking -{ - [DataContract] - public class NetworkPoint : ICloneable, IEquatable - - { - [IgnoreDataMember] - public IPAddress Address { get; set; } - - [DataMember(Name = "Address", Order = 0)] - public string DataPublicIpAddress - { - get => Address.ToString(); - set => Address = string.IsNullOrEmpty(value) ? null : IPAddress.Parse(value); - } - - [DataMember(Order = 1)] - public ushort Port { get; set; } - - public NetworkPoint(IPAddress address, ushort port) - { - Address = address; - Port = port; - } - - public NetworkPoint(NetworkPoint networkPoint) - { - string ip = networkPoint.Address.ToString(); - Address = string.IsNullOrEmpty(ip) ? null : IPAddress.Parse(ip); - Port = networkPoint.Port; - } - - public NetworkPoint(IPEndPoint ipEndPoint) - { - Address = ipEndPoint.Address; - Port = (ushort) ipEndPoint.Port; - } - - public IPEndPoint ToIpEndPoint() - { - return new IPEndPoint(Address, Port); - } - - public object Clone() - { - return new NetworkPoint(this); - } - - public bool Equals(NetworkPoint other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return other.DataPublicIpAddress == DataPublicIpAddress && other.Port == Port; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; - return Equals((NetworkPoint) obj); - } - - public override int GetHashCode() - { - unchecked - { - return ((DataPublicIpAddress != null ? DataPublicIpAddress.GetHashCode() : 0) * 397) ^ Port.GetHashCode(); - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/ServerBridge/Bridge.cs b/Arrowgene.Services/Networking/ServerBridge/Bridge.cs index c6cff0c..3fb87d4 100644 --- a/Arrowgene.Services/Networking/ServerBridge/Bridge.cs +++ b/Arrowgene.Services/Networking/ServerBridge/Bridge.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using Arrowgene.Services.Logging; +using Arrowgene.Logging; using Arrowgene.Services.Networking.ServerBridge.Messages; namespace Arrowgene.Services.Networking.ServerBridge diff --git a/Arrowgene.Services/Networking/ServerBridge/MemoryBridge.cs b/Arrowgene.Services/Networking/ServerBridge/MemoryBridge.cs index 8938232..aa99791 100644 --- a/Arrowgene.Services/Networking/ServerBridge/MemoryBridge.cs +++ b/Arrowgene.Services/Networking/ServerBridge/MemoryBridge.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using Arrowgene.Services.Logging; +using Arrowgene.Logging; using Arrowgene.Services.Networking.ServerBridge.Messages; namespace Arrowgene.Services.Networking.ServerBridge diff --git a/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridge.cs b/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridge.cs index 45a6cc5..0dc4a37 100644 --- a/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridge.cs +++ b/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridge.cs @@ -1,13 +1,14 @@ using System; using System.Collections.Generic; using System.Net; +using Arrowgene.Networking; +using Arrowgene.Networking.Tcp; +using Arrowgene.Networking.Tcp.Client; +using Arrowgene.Networking.Tcp.Client.SyncReceive; +using Arrowgene.Networking.Tcp.Consumer; +using Arrowgene.Networking.Tcp.Server.AsyncEvent; using Arrowgene.Services.Networking.ServerBridge.Messages; -using Arrowgene.Services.Networking.Tcp; -using Arrowgene.Services.Networking.Tcp.Client; -using Arrowgene.Services.Networking.Tcp.Client.SyncReceive; -using Arrowgene.Services.Networking.Tcp.Consumer; using Arrowgene.Services.Networking.Tcp.Consumer.GenericConsumption; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; namespace Arrowgene.Services.Networking.ServerBridge.Tcp { diff --git a/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeRegistration.cs b/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeRegistration.cs index 927a86c..b870fb3 100644 --- a/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeRegistration.cs +++ b/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeRegistration.cs @@ -1,4 +1,5 @@ using System; +using Arrowgene.Networking; using Arrowgene.Services.Networking.ServerBridge.Messages; namespace Arrowgene.Services.Networking.ServerBridge.Tcp diff --git a/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeSettings.cs b/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeSettings.cs index b7ec243..7a485b3 100644 --- a/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeSettings.cs +++ b/Arrowgene.Services/Networking/ServerBridge/Tcp/TcpBridgeSettings.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.Serialization; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; +using Arrowgene.Networking; +using Arrowgene.Networking.Tcp.Server.AsyncEvent; namespace Arrowgene.Services.Networking.ServerBridge.Tcp { diff --git a/Arrowgene.Services/Networking/ServerBridge/Udp/UdpBridge.cs b/Arrowgene.Services/Networking/ServerBridge/Udp/UdpBridge.cs index 3ba9615..b7648d0 100644 --- a/Arrowgene.Services/Networking/ServerBridge/Udp/UdpBridge.cs +++ b/Arrowgene.Services/Networking/ServerBridge/Udp/UdpBridge.cs @@ -1,6 +1,6 @@ using System.Net; +using Arrowgene.Networking.Udp; using Arrowgene.Services.Networking.ServerBridge.Messages; -using Arrowgene.Services.Networking.Udp; using Arrowgene.Services.Serialization; namespace Arrowgene.Services.Networking.ServerBridge.Udp diff --git a/Arrowgene.Services/Networking/SocketOption.cs b/Arrowgene.Services/Networking/SocketOption.cs deleted file mode 100644 index 36b0800..0000000 --- a/Arrowgene.Services/Networking/SocketOption.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Net.Sockets; -using System.Runtime.Serialization; - -namespace Arrowgene.Services.Networking -{ - [DataContract] - public class SocketOption : ICloneable, IEquatable - { - [DataMember(Name = "Level", Order = 0)] - public string DataLevel - { - get => Level.ToString(); - set => Level = ParseEnum(value); - } - - [DataMember(Order = 1)] - public SocketOptionName Name { get; set; } - - [DataMember(Order = 2)] - public object Value { get; set; } - - [IgnoreDataMember] - public SocketOptionLevel Level { get; set; } - - public SocketOption(SocketOptionLevel level, SocketOptionName name, object value) - { - Level = level; - Name = name; - Value = value; - } - - public SocketOption(SocketOption socketOption) - { - Level = socketOption.Level; - Name = socketOption.Name; - Value = socketOption.Value; - } - - public object Clone() - { - return new SocketOption(this); - } - - private T ParseEnum(string value) where T : struct - { - if (!Enum.TryParse(value, true, out T instance)) - { - instance = default(T); - } - - return instance; - } - - public bool Equals(SocketOption other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return Equals(Value, other.Value) && Level == other.Level && Name == other.Name; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((SocketOption) obj); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Value != null ? Value.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (int) Level; - hashCode = (hashCode * 397) ^ (int) Name; - return hashCode; - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/SocketSettings.cs b/Arrowgene.Services/Networking/SocketSettings.cs deleted file mode 100644 index 075336e..0000000 --- a/Arrowgene.Services/Networking/SocketSettings.cs +++ /dev/null @@ -1,275 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Sockets; -using System.Runtime.Serialization; -using Arrowgene.Services.Logging; - -namespace Arrowgene.Services.Networking -{ - [DataContract] - public class SocketSettings : ICloneable - { - public SocketSettings() - { - Backlog = 5; - DualMode = false; - ExclusiveAddressUse = false; - NoDelay = false; - UseOnlyOverlappedIo = false; - ReceiveBufferSize = 8192; - ReceiveTimeout = 0; - SendBufferSize = 8192; - SendTimeout = 0; - DontFragment = true; - Ttl = 32; - LingerEnabled = false; - LingerTime = 30; - SocketOptions = new List(); - AddSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); - } - - public SocketSettings(SocketSettings socketSettings) - { - Backlog = socketSettings.Backlog; - DualMode = socketSettings.DualMode; - ExclusiveAddressUse = socketSettings.ExclusiveAddressUse; - NoDelay = socketSettings.NoDelay; - UseOnlyOverlappedIo = socketSettings.UseOnlyOverlappedIo; - ReceiveBufferSize = socketSettings.ReceiveBufferSize; - ReceiveTimeout = socketSettings.ReceiveTimeout; - SendBufferSize = socketSettings.SendBufferSize; - SendTimeout = socketSettings.SendTimeout; - DontFragment = socketSettings.DontFragment; - Ttl = socketSettings.Ttl; - LingerEnabled = socketSettings.LingerEnabled; - LingerTime = socketSettings.LingerTime; - SocketOptions = new List(); - foreach (SocketOption socketOption in socketSettings.SocketOptions) - { - SocketOptions.Add(new SocketOption(socketOption)); - } - } - - /// The maximum length of the pending connections queue. - [DataMember(Order = 1)] - public int Backlog { get; set; } - - /// Gets or sets a value that specifies whether the allows Internet Protocol (IP) datagrams to be fragmented. - /// true if the allows datagram fragmentation; otherwise, false. The default is true. - /// This property can be set only for sockets in the or families. - [DataMember(Order = 2)] - public bool DontFragment { get; set; } - - /// Gets or sets a value that specifies whether the is a dual-mode socket used for both IPv4 and IPv6. - /// true if the is a dual-mode socket; otherwise, false. The default is false. - [DataMember(Order = 3)] - public bool DualMode { get; set; } - - /// Gets or sets a value that specifies whether the allows only one process to bind to a port. - /// true if the allows only one socket to bind to a specific port; otherwise, false. The default is true for Windows Server 2003 and Windows XP Service Pack 2, and false for all other versions. - [DataMember(Order = 4)] - public bool ExclusiveAddressUse { get; set; } - - /// Gets or sets a value that specifies whether the stream is using the Nagle algorithm. - /// false if the uses the Nagle algorithm; otherwise, true. The default is false. - [DataMember(Order = 5)] - public bool NoDelay { get; set; } - - /// Specifies whether the socket should only use Overlapped I/O mode. - /// true if the uses only overlapped I/O; otherwise, false. The default is false. - /// The socket has been bound to a completion port. - [DataMember(Order = 6)] - public bool UseOnlyOverlappedIo { get; set; } - - /// Gets or sets a value that specifies the size of the receive buffer of the . - /// An that contains the size, in bytes, of the receive buffer. The default is 8192. - /// The value specified for a set operation is less than 0. - [DataMember(Order = 7)] - public int ReceiveBufferSize { get; set; } - - /// Gets or sets a value that specifies the amount of time after which a synchronous call will time out. - /// The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period. - /// The value specified for a set operation is less than -1. - [DataMember(Order = 8)] - public int ReceiveTimeout { get; set; } - - /// Gets or sets a value that specifies the size of the send buffer of the . - /// An that contains the size, in bytes, of the send buffer. The default is 8192. - /// The value specified for a set operation is less than 0. - [DataMember(Order = 9)] - public int SendBufferSize { get; set; } - - /// Gets or sets a value that specifies the amount of time after which a synchronous call will time out. - /// The time-out value, in milliseconds. If you set the property with a value between 1 and 499, the value will be changed to 500. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period. - /// The value specified for a set operation is less than -1. - [DataMember(Order = 10)] - public int SendTimeout { get; set; } - - /// Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the . The TTL value may be set to a value from 0 to 255. When this property is not set, the default TTL value for a socket is 32. - /// The TTL value. - /// The TTL value can't be set to a negative number. - /// This property can be set only for sockets in the or families. - /// An error occurred when attempting to access the socket. This error is also returned when an attempt was made to set TTL to a value higher than 255. - [DataMember(Order = 11)] - public short Ttl { get; set; } - - /// Gets or sets a value that specifies whether the will delay closing a socket in an attempt to send all pending data. - /// Gets or sets a value that indicates whether to linger after the is closed. - /// true if the should linger after is called; otherwise, false. - [DataMember(Order = 12)] - public bool LingerEnabled { get; set; } - - /// Gets or sets a value that specifies whether the will delay closing a socket in an attempt to send all pending data. - /// Gets or sets the amount of time to remain connected after calling the method if data remains to be sent. - /// The amount of time, in seconds, to remain connected after calling . - [DataMember(Order = 13)] - public int LingerTime { get; set; } - - [DataMember(Order = 14)] public List SocketOptions { get; set; } - - public void AddSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue) - { - AddSocketOption(new SocketOption(optionLevel, optionName, optionValue)); - } - - public void AddSocketOption(SocketOption socketOption) - { - SocketOptions.Add(socketOption); - } - - public void SetSocketOptions(Socket socket, ILogger logger = null) - { - foreach (SocketOption option in SocketOptions) - { - try - { - socket.SetSocketOption(option.Level, option.Name, option.Value); - } - catch (Exception) - { - logger?.Debug( - $"Ignoring Socket Option: (Level:{option?.Level} Name:{option?.Name} Value:{option?.Value})"); - } - } - } - - public void ConfigureSocket(Socket socket, ILogger logger = null) - { - if (socket.SocketType == SocketType.Dgram) - { - try - { - socket.DontFragment = DontFragment; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: DontFragment"); - } - } - - if (socket.AddressFamily == AddressFamily.InterNetworkV6) - { - try - { - socket.DualMode = DualMode; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: DualMode"); - } - } - - try - { - socket.ExclusiveAddressUse = ExclusiveAddressUse; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: ExclusiveAddressUse"); - } - - try - { - socket.LingerState = new LingerOption(LingerEnabled, LingerTime); - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: LingerState"); - } - - try - { - socket.NoDelay = NoDelay; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: NoDelay"); - } - - try - { - socket.ReceiveBufferSize = ReceiveBufferSize; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: ReceiveBufferSize"); - } - - - try - { - socket.ReceiveTimeout = ReceiveTimeout; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: ReceiveTimeout"); - } - - - try - { - socket.SendBufferSize = SendBufferSize; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: SendBufferSize"); - } - - try - { - socket.SendTimeout = SendTimeout; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: SendTimeout"); - } - - try - { - socket.Ttl = Ttl; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: Ttl"); - } - - - try - { - socket.UseOnlyOverlappedIO = UseOnlyOverlappedIo; - } - catch (Exception) - { - logger?.Debug("Ignoring Socket Setting: UseOnlyOverlappedIo"); - } - - SetSocketOptions(socket); - } - - - public object Clone() - { - return new SocketSettings(this); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Client/ConnectErrorEventArgs.cs b/Arrowgene.Services/Networking/Tcp/Client/ConnectErrorEventArgs.cs deleted file mode 100644 index c238327..0000000 --- a/Arrowgene.Services/Networking/Tcp/Client/ConnectErrorEventArgs.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -// ReSharper disable MemberCanBePrivate.Global -// ReSharper disable UnusedAutoPropertyAccessor.Global - -using System; -using System.Net; - -namespace Arrowgene.Services.Networking.Tcp.Client -{ - public class ConnectErrorEventArgs : EventArgs - { - public ConnectErrorEventArgs(ITcpClient client, string reason, IPAddress serverIpAddress, int serverPort, TimeSpan timeout) - { - Client = client; - Reason = reason; - ServerIpAddress = serverIpAddress; - ServerPort = serverPort; - Timeout = timeout; - } - - public ITcpClient Client { get; } - public string Reason { get; } - public IPAddress ServerIpAddress { get; } - public int ServerPort { get; } - public TimeSpan Timeout { get; } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Client/ITcpClient.cs b/Arrowgene.Services/Networking/Tcp/Client/ITcpClient.cs deleted file mode 100644 index 14d5937..0000000 --- a/Arrowgene.Services/Networking/Tcp/Client/ITcpClient.cs +++ /dev/null @@ -1,37 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -// ReSharper disable EventNeverSubscribedTo.Global - -using System; -using System.Net; - -namespace Arrowgene.Services.Networking.Tcp.Client -{ - public interface ITcpClient : ITcpSocket - { - void Connect(IPAddress serverIpAddress, ushort serverPort, TimeSpan timeout); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Client/SyncReceive/SyncReceiveTcpClient.cs b/Arrowgene.Services/Networking/Tcp/Client/SyncReceive/SyncReceiveTcpClient.cs deleted file mode 100644 index b9209a5..0000000 --- a/Arrowgene.Services/Networking/Tcp/Client/SyncReceive/SyncReceiveTcpClient.cs +++ /dev/null @@ -1,217 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using Arrowgene.Services.Buffers; -using Arrowgene.Services.Exceptions; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp.Consumer; - -namespace Arrowgene.Services.Networking.Tcp.Client.SyncReceive -{ - public class SyncReceiveTcpClient : TcpClient - { - private const string DefaultName = "Tcp Client"; - - private volatile bool _isConnected; - private readonly int _pollTimeout; - private readonly int _bufferSize; - private readonly ILogger _logger; - private Socket _socket; - private Thread _readThread; - - - public IBufferProvider BufferProvider { get; } - public int SocketPollTimeout { get; } - public int ThreadJoinTimeout { get; } - public string Name { get; set; } - - public override bool IsAlive => _isConnected; - - public SyncReceiveTcpClient(IConsumer consumer) : base(consumer) - { - BufferProvider = new StreamBuffer(); - _logger = LogProvider.Logger(this); - SocketPollTimeout = 100; - Name = DefaultName; - ThreadJoinTimeout = 1000; - _pollTimeout = 10; - _bufferSize = 1024; - } - - public override void Send(byte[] payload) - { - _socket.Send(payload); - } - - protected override void OnConnect(IPAddress remoteIpAddress, ushort serverPort, TimeSpan timeout) - { - if (!_isConnected) - { - if (remoteIpAddress == null || serverPort <= 0) - { - throw new InvalidParameterException($"Address({remoteIpAddress}) or Port({serverPort}) invalid"); - } - - RemoteIpAddress = remoteIpAddress; - Port = serverPort; - try - { - Socket socket = CreateSocket(); - if (socket != null) - { - if (timeout != TimeSpan.Zero) - { - IAsyncResult result = socket.BeginConnect(RemoteIpAddress, Port, null, null); - bool success = result.AsyncWaitHandle.WaitOne(timeout, true); - if (socket.Connected && success) - { - socket.EndConnect(result); - ConnectionEstablished(socket); - } - else - { - const string errTimeout = "Client connection timed out."; - _logger.Error(errTimeout); - socket.Close(); - OnConnectError(this, errTimeout, RemoteIpAddress, Port, timeout); - } - } - else - { - socket.Connect(RemoteIpAddress, Port); - ConnectionEstablished(socket); - } - } - else - { - const string errConnect = "Client could not connect."; - _logger.Error(errConnect); - OnConnectError(this, errConnect, RemoteIpAddress, Port, timeout); - } - } - catch (Exception exception) - { - _logger.Exception(exception); - OnConnectError(this, exception.Message, RemoteIpAddress, Port, timeout); - } - } - else - { - const string errConnected = "Client is already connected."; - _logger.Error(errConnected); - OnConnectError(this, errConnected, RemoteIpAddress, Port, timeout); - } - } - - protected override void OnClose() - { - _isConnected = false; - Service.JoinThread(_readThread, ThreadJoinTimeout, _logger); - - if (_socket != null) - { - _socket.Close(); - } - - _logger.Debug($"{Name} Closed"); - OnClientDisconnected(this); - } - - private Socket CreateSocket() - { - Socket socket; - _logger.Info($"{Name} Creating Socket..."); - if (RemoteIpAddress.AddressFamily == AddressFamily.InterNetworkV6) - { - socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); - _logger.Info($"{Name} Created Socket (IPv6)"); - } - else - { - socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - _logger.Info($"{Name} Created Socket (IPv4)"); - } - - return socket; - } - - private void ConnectionEstablished(Socket socket) - { - _socket = socket; - _readThread = new Thread(ReadProcess); - _readThread.Name = Name; - _readThread.Start(); - _logger.Info($"{Name} connected"); - OnClientConnected(this); - } - - private void ReadProcess() - { - _logger.Info($"{Name} started."); - _isConnected = true; - IBuffer payload = BufferProvider.Provide(); - while (_isConnected) - { - if (_socket.Poll(_pollTimeout, SelectMode.SelectRead)) - { - byte[] buffer = new byte[_bufferSize]; - try - { - int bytesReceived; - while (_socket.Available > 0 && - (bytesReceived = _socket.Receive(buffer, 0, _bufferSize, SocketFlags.None)) > 0) - { - payload.WriteBytes(buffer, 0, bytesReceived); - } - } - catch (Exception e) - { - if (!_socket.Connected) - { - _logger.Error($"{Name} {e.Message}"); - } - else - { - _logger.Exception(e); - } - - Close(); - } - - payload.SetPositionStart(); - OnReceivedData(this, payload.GetAllBytes()); - } - - Thread.Sleep(SocketPollTimeout); - } - - _logger.Info($"{Name} ended."); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Client/TcpClient.cs b/Arrowgene.Services/Networking/Tcp/Client/TcpClient.cs deleted file mode 100644 index d4d2629..0000000 --- a/Arrowgene.Services/Networking/Tcp/Client/TcpClient.cs +++ /dev/null @@ -1,112 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Net; -using Arrowgene.Services.Networking.Tcp.Consumer; - -namespace Arrowgene.Services.Networking.Tcp.Client -{ - public abstract class TcpClient : ITcpClient - { - private readonly IConsumer _consumer; - - protected TcpClient(IConsumer consumer) - { - _consumer = consumer; - } - - public abstract bool IsAlive { get; } - - public event EventHandler ConnectError; - - public IPAddress RemoteIpAddress { get; protected set; } - public ushort Port { get; protected set; } - public int UnitOfOrder => 0; - public DateTime LastActive { get; set; } - - public abstract void Send(byte[] payload); - - public void Connect(IPAddress serverIpAddress, ushort serverPort, TimeSpan timeout) - { - _consumer.OnStart(); - OnConnect(serverIpAddress, serverPort, timeout); - } - - public void Connect(string remoteIpAddress, ushort serverPort, TimeSpan timeout) - { - Connect(IPAddress.Parse(remoteIpAddress), serverPort, timeout); - } - - public void Close() - { - OnClose(); - _consumer.OnStop(); - } - - public string Identity - { - get - { - if (RemoteIpAddress != null) - { - return RemoteIpAddress.ToString(); - } - - return GetHashCode().ToString(); - } - } - - protected abstract void OnConnect(IPAddress serverIpAddress, ushort serverPort, TimeSpan timeout); - protected abstract void OnClose(); - - protected void OnReceivedData(ITcpSocket socket, byte[] data) - { - _consumer.OnReceivedData(socket, data); - } - - protected void OnClientDisconnected(ITcpSocket socket) - { - _consumer.OnClientDisconnected(socket); - } - - protected void OnClientConnected(ITcpSocket socket) - { - _consumer.OnClientConnected(socket); - } - - protected void OnConnectError(ITcpClient client, string reason, IPAddress serverIpAddress, ushort serverPort, - TimeSpan timeout) - { - EventHandler connectError = ConnectError; - if (connectError != null) - { - ConnectErrorEventArgs connectErrorEventArgsEventArgs = - new ConnectErrorEventArgs(client, reason, serverIpAddress, serverPort, timeout); - connectError(this, connectErrorEventArgsEventArgs); - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/BlockingQueueConsumer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/BlockingQueueConsumer.cs deleted file mode 100644 index 6951945..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/BlockingQueueConsumer.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System.Collections.Concurrent; - -namespace Arrowgene.Services.Networking.Tcp.Consumer.BlockingQueueConsumption -{ - public class BlockingQueueConsumer : IConsumer - { - public BlockingCollection ClientEvents; - - public void OnStart() - { - ClientEvents = new BlockingCollection(); - } - - public void OnStarted() - { - } - - public void OnReceivedData(ITcpSocket socket, byte[] data) - { - ClientEvents.Add(new ClientEvent(socket, ClientEventType.ReceivedData, data)); - } - - public void OnClientDisconnected(ITcpSocket socket) - { - ClientEvents.Add(new ClientEvent(socket, ClientEventType.Disconnected)); - } - - public void OnClientConnected(ITcpSocket socket) - { - ClientEvents.Add(new ClientEvent(socket, ClientEventType.Connected)); - } - - public void OnStop() - { - } - - public void OnStopped() - { - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ClientEvent.cs b/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ClientEvent.cs deleted file mode 100644 index 40d76ed..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ClientEvent.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -namespace Arrowgene.Services.Networking.Tcp.Consumer.BlockingQueueConsumption -{ - public class ClientEvent - { - public ClientEventType ClientEventType { get; } - public byte[] Data { get; } - public ITcpSocket Socket { get; } - - public ClientEvent(ITcpSocket socket, ClientEventType clientEventType, byte[] data = null) - { - Socket = socket; - ClientEventType = clientEventType; - Data = data; - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ClientEventType.cs b/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ClientEventType.cs deleted file mode 100644 index 5450d8f..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ClientEventType.cs +++ /dev/null @@ -1,34 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -namespace Arrowgene.Services.Networking.Tcp.Consumer.BlockingQueueConsumption -{ - public enum ClientEventType - { - Connected, - ReceivedData, - Disconnected - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ThreadedBlockingQueueConsumer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ThreadedBlockingQueueConsumer.cs deleted file mode 100644 index ff44981..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/BlockingQueueConsumption/ThreadedBlockingQueueConsumer.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Threading; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp.Server.AsyncEvent; - -namespace Arrowgene.Services.Networking.Tcp.Consumer.BlockingQueueConsumption -{ - /** - * Consumer creates number of threads based on `AsyncEventSettings.MaxUnitOfOrder`. - * Handle*-methods will be called from various threads with order of packets preserved. - */ - public abstract class ThreadedBlockingQueueConsumer : IConsumer - { - private readonly BlockingCollection[] _queues; - private readonly Thread[] _threads; - private readonly ILogger _logger; - private readonly int _maxUnitOfOrder; - private volatile bool _isRunning; - private readonly string _identity; - - private CancellationTokenSource _cancellationTokenSource; - - public ThreadedBlockingQueueConsumer(AsyncEventSettings socketSetting, - string identity = "ThreadedBlockingQueueConsumer") - { - _logger = LogProvider.Logger(this); - _maxUnitOfOrder = socketSetting.MaxUnitOfOrder; - _identity = identity; - _queues = new BlockingCollection[_maxUnitOfOrder]; - _threads = new Thread[_maxUnitOfOrder]; - } - - protected abstract void HandleReceived(ITcpSocket socket, byte[] data); - protected abstract void HandleDisconnected(ITcpSocket socket); - protected abstract void HandleConnected(ITcpSocket socket); - - private void Consume(int unitOfOrder) - { - while (_isRunning) - { - ClientEvent clientEvent; - try - { - clientEvent = _queues[unitOfOrder].Take(_cancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - return; - } - - switch (clientEvent.ClientEventType) - { - case ClientEventType.ReceivedData: - HandleReceived(clientEvent.Socket, clientEvent.Data); - break; - case ClientEventType.Connected: - HandleConnected(clientEvent.Socket); - break; - case ClientEventType.Disconnected: - HandleDisconnected(clientEvent.Socket); - break; - } - } - } - - void IConsumer.OnStart() - { - if (_isRunning) - { - _logger.Error($"[{_identity}] Consumer already running."); - return; - } - - _cancellationTokenSource = new CancellationTokenSource(); - _isRunning = true; - for (int i = 0; i < _maxUnitOfOrder; i++) - { - int uuo = i; - _queues[i] = new BlockingCollection(); - _threads[i] = new Thread(() => Consume(uuo)); - _threads[i].Name = $"[{_identity}] Consumer: {i}"; - _logger.Info($"[{_identity}] Starting Consumer: {i}"); - _threads[i].Start(); - } - } - - void IConsumer.OnStarted() - { - } - - void IConsumer.OnReceivedData(ITcpSocket socket, byte[] data) - { - _queues[socket.UnitOfOrder].Add(new ClientEvent(socket, ClientEventType.ReceivedData, data)); - } - - void IConsumer.OnClientDisconnected(ITcpSocket socket) - { - _queues[socket.UnitOfOrder].Add(new ClientEvent(socket, ClientEventType.Disconnected)); - } - - void IConsumer.OnClientConnected(ITcpSocket socket) - { - _queues[socket.UnitOfOrder].Add(new ClientEvent(socket, ClientEventType.Connected)); - } - - void IConsumer.OnStop() - { - if (!_isRunning) - { - _logger.Error($"[{_identity}] Consumer already stopped."); - return; - } - - _isRunning = false; - _cancellationTokenSource.Cancel(); - for (int i = 0; i < _maxUnitOfOrder; i++) - { - Thread consumerThread = _threads[i]; - _logger.Info($"[{_identity}] Shutting Consumer: {i} down..."); - Service.JoinThread(consumerThread, 10000, _logger); - _logger.Info($"[{_identity}] Consumer: {i} ended."); - _threads[i] = null; - } - } - - void IConsumer.OnStopped() - { - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/ConnectedEventArgs.cs b/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/ConnectedEventArgs.cs deleted file mode 100644 index 8db0faa..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/ConnectedEventArgs.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; - -namespace Arrowgene.Services.Networking.Tcp.Consumer.EventConsumption -{ - public class ConnectedEventArgs : EventArgs - { - public ConnectedEventArgs(ITcpSocket socket) - { - Socket = socket; - } - - public ITcpSocket Socket { get; } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/DisconnectedEventArgs.cs b/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/DisconnectedEventArgs.cs deleted file mode 100644 index eca8373..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/DisconnectedEventArgs.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; - -namespace Arrowgene.Services.Networking.Tcp.Consumer.EventConsumption -{ - public class DisconnectedEventArgs : EventArgs - { - public DisconnectedEventArgs(ITcpSocket socket) - { - Socket = socket; - } - - public ITcpSocket Socket { get; } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/EventConsumer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/EventConsumer.cs deleted file mode 100644 index 4f3bd89..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/EventConsumer.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; - -namespace Arrowgene.Services.Networking.Tcp.Consumer.EventConsumption -{ - public class EventConsumer : IConsumer - { - /// - /// Occures when a client disconnected. - /// - public event EventHandler ClientDisconnected; - - /// - /// Occures when a client connected. - /// - public event EventHandler ClientConnected; - - /// - /// Occures when a packet is received. - /// - public event EventHandler ReceivedPacket; - - - public void OnStart() - { - } - - public void OnStarted() - { - - } - - public void OnReceivedData(ITcpSocket socket, byte[] data) - { - EventHandler receivedPacket = ReceivedPacket; - if (receivedPacket != null) - { - ReceivedPacketEventArgs receivedPacketEventArgs = new ReceivedPacketEventArgs(socket, data); - receivedPacket(this, receivedPacketEventArgs); - } - } - - public void OnClientDisconnected(ITcpSocket socket) - { - EventHandler clientDisconnected = ClientDisconnected; - if (clientDisconnected != null) - { - DisconnectedEventArgs clientDisconnectedEventArgs = new DisconnectedEventArgs(socket); - clientDisconnected(this, clientDisconnectedEventArgs); - } - } - - public void OnClientConnected(ITcpSocket socket) - { - EventHandler clientConnected = ClientConnected; - if (clientConnected != null) - { - ConnectedEventArgs clientConnectedEventArgs = new ConnectedEventArgs(socket); - clientConnected(this, clientConnectedEventArgs); - } - } - - public void OnStop() - { - } - - public void OnStopped() - { - - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/ReceivedPacketEventArgs.cs b/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/ReceivedPacketEventArgs.cs deleted file mode 100644 index 280b3c1..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/EventConsumption/ReceivedPacketEventArgs.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; - -namespace Arrowgene.Services.Networking.Tcp.Consumer.EventConsumption -{ - public class ReceivedPacketEventArgs : EventArgs - { - public ReceivedPacketEventArgs(ITcpSocket socket, byte[] data) - { - Socket = socket; - Data = data; - } - - public ITcpSocket Socket { get; } - - public byte[] Data { get; } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericConsumer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericConsumer.cs index d0af81e..435d6f9 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericConsumer.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericConsumer.cs @@ -1,31 +1,8 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; +using System; using System.Collections.Generic; -using Arrowgene.Services.Buffers; +using Arrowgene.Buffers; +using Arrowgene.Networking.Tcp; +using Arrowgene.Networking.Tcp.Consumer; using Arrowgene.Services.Serialization; namespace Arrowgene.Services.Networking.Tcp.Consumer.GenericConsumption diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericState.cs b/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericState.cs index 1d47c31..613d4e3 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericState.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/GenericState.cs @@ -1,29 +1,4 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using Arrowgene.Services.Buffers; +using Arrowgene.Buffers; namespace Arrowgene.Services.Networking.Tcp.Consumer.GenericConsumption { diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/ReceivedGenericEventArgs.cs b/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/ReceivedGenericEventArgs.cs index 045a3e2..17f5745 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/ReceivedGenericEventArgs.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/GenericConsumption/ReceivedGenericEventArgs.cs @@ -1,29 +1,5 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; +using System; +using Arrowgene.Networking.Tcp; namespace Arrowgene.Services.Networking.Tcp.Consumer.GenericConsumption { diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/IConsumer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/IConsumer.cs deleted file mode 100644 index 80af219..0000000 --- a/Arrowgene.Services/Networking/Tcp/Consumer/IConsumer.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -namespace Arrowgene.Services.Networking.Tcp.Consumer -{ - public interface IConsumer - { - void OnStart(); - void OnStarted(); - void OnReceivedData(ITcpSocket socket, byte[] data); - void OnClientDisconnected(ITcpSocket socket); - void OnClientConnected(ITcpSocket socket); - void OnStop(); - void OnStopped(); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageHandle.cs b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageHandle.cs index 7af0b22..04e4a06 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageHandle.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageHandle.cs @@ -1,27 +1,4 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - +using Arrowgene.Networking.Tcp; namespace Arrowgene.Services.Networking.Tcp.Consumer.Messages { diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageSerializer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageSerializer.cs index d2d31a8..089bdb7 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageSerializer.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/IMessageSerializer.cs @@ -1,29 +1,4 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -namespace Arrowgene.Services.Networking.Tcp.Consumer.Messages +namespace Arrowgene.Services.Networking.Tcp.Consumer.Messages { public interface IMessageSerializer { diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/Message.cs b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/Message.cs index d839aa4..f28b3bc 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/Message.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/Message.cs @@ -1,29 +1,4 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; +using System; namespace Arrowgene.Services.Networking.Tcp.Consumer.Messages { diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageConsumer.cs b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageConsumer.cs index edbffac..f427006 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageConsumer.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageConsumer.cs @@ -1,30 +1,6 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; +using System; using System.Collections.Generic; +using Arrowgene.Networking.Tcp; using Arrowgene.Services.Networking.Tcp.Consumer.GenericConsumption; namespace Arrowgene.Services.Networking.Tcp.Consumer.Messages diff --git a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageHandle.cs b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageHandle.cs index a00e99f..904fb3c 100644 --- a/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageHandle.cs +++ b/Arrowgene.Services/Networking/Tcp/Consumer/Messages/MessageHandle.cs @@ -1,27 +1,4 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - +using Arrowgene.Networking.Tcp; namespace Arrowgene.Services.Networking.Tcp.Consumer.Messages { diff --git a/Arrowgene.Services/Networking/Tcp/ITcpSocket.cs b/Arrowgene.Services/Networking/Tcp/ITcpSocket.cs deleted file mode 100644 index a40f7b3..0000000 --- a/Arrowgene.Services/Networking/Tcp/ITcpSocket.cs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Net; - -namespace Arrowgene.Services.Networking.Tcp -{ - public interface ITcpSocket - { - string Identity { get; } - IPAddress RemoteIpAddress { get; } - ushort Port { get; } - - /// - /// Allows for distribution among multiple queues. - /// - int UnitOfOrder { get; } - - /// - /// Timestamp of last recv/send operation. - /// - DateTime LastActive { get; set; } - - /// - /// Determines if this socket can be used for send/recv. - /// - bool IsAlive { get; } - - void Send(byte[] data); - void Close(); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventClient.cs b/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventClient.cs deleted file mode 100644 index 52d1a11..0000000 --- a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventClient.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Net; -using System.Net.Sockets; - -namespace Arrowgene.Services.Networking.Tcp.Server.AsyncEvent -{ - public class AsyncEventClient : ITcpSocket - { - public string Identity { get; } - public IPAddress RemoteIpAddress { get; } - public ushort Port { get; } - public int UnitOfOrder { get; } - - public bool IsAlive - { - get - { - lock (_lock) - { - return _isAlive; - } - } - } - - public Socket Socket { get; } - public SocketAsyncEventArgs ReadEventArgs { get; private set; } - public DateTime LastActive { get; set; } - - private bool _isAlive; - private readonly AsyncEventServer _server; - private readonly object _lock; - - public AsyncEventClient(Socket socket, SocketAsyncEventArgs readEventArgs, AsyncEventServer server, int uoo) - { - _lock = new object(); - _isAlive = true; - Socket = socket; - ReadEventArgs = readEventArgs; - _server = server; - UnitOfOrder = uoo; - LastActive = DateTime.Now; - if (Socket.RemoteEndPoint is IPEndPoint ipEndPoint) - { - RemoteIpAddress = ipEndPoint.Address; - Port = (ushort) ipEndPoint.Port; - } - - Identity = $"{RemoteIpAddress}:{Port}"; - } - - public void Send(byte[] data) - { - _server.Send(this, data); - } - - public void Close() - { - lock (_lock) - { - if (!_isAlive) - { - return; - } - - _isAlive = false; - } - - try - { - Socket.Shutdown(SocketShutdown.Both); - } - catch - { - // ignored - } - - Socket.Close(); - _server.NotifyDisconnected(this); - ReadEventArgs = null; - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventServer.cs b/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventServer.cs deleted file mode 100644 index 0edb6d6..0000000 --- a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventServer.cs +++ /dev/null @@ -1,674 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using Arrowgene.Services.Collections; -using Arrowgene.Services.Logging; -using Arrowgene.Services.Networking.Tcp.Consumer; - -namespace Arrowgene.Services.Networking.Tcp.Server.AsyncEvent -{ - /* - * I found that the AsyncTcpSession.SendInternal, AsyncTcpSession. - * StartReceive and AsyncTcpSession.SetBuffer can be using the same instance of SocketAsyncEventArgs without locking. - * However, the SocketAsyncEventArgs internally excludes data-sending, data-receiving and buffer-setting operations mutually. - * Those three operations can not proceed at the same time. - * Consequently, the SetBuffer method can fail when the Socket is using the SocketAsyncEventArgs instance to receive or send data and - * therefore the InvalidOperationException is thrown. Thread synchronization shall be deployed to avoid the above problem. - */ - - /// - /// Implementation of socket server using AsyncEventArgs. - /// - /// - Preallocate all objects -> No further allocations during runtime. - /// - Support UnitOfOrder -> Enables to simultaneously process tcp packages and preserving order. - /// - Support SocketTimeout -> Prevent half-open connections by closing the socket if last recv/send time is larger. - /// - public class AsyncEventServer : TcpServer - { - private const string ServerThreadName = "AsyncEventServer"; - private const string TimeoutThreadName = "AsyncEventServer_Timeout"; - private const int ThreadTimeoutMs = 10000; - private const int NumAccepts = 10; - - private readonly ConcurrentStack _receivePool; - private readonly ConcurrentStack _sendPool; - private readonly ConcurrentStack _acceptPool; - private readonly SemaphoreSlim _maxNumberAcceptedClients; - private readonly SemaphoreSlim _maxNumberAccepts; - - private readonly SemaphoreSlim _maxNumberSendOperations; - - private readonly byte[] _buffer; - private readonly ILogger _logger; - private readonly AsyncEventSettings _settings; - private readonly TimeSpan _socketTimeout; - private readonly int[] _unitOfOrders; - private readonly object _unitOfOrderLock; - private readonly object _isRunningLock; - private readonly string _identity; - private readonly LockList _clients; - - private Thread _serverThread; - private Thread _timeoutThread; - private Socket _listenSocket; - private CancellationTokenSource _cancellation; - private long _acceptedConnections; - private volatile bool _isRunning; - - public AsyncEventServer(IPAddress ipAddress, ushort port, IConsumer consumer, AsyncEventSettings settings) - : base(ipAddress, port, consumer) - { - _clients = new LockList(); - _settings = new AsyncEventSettings(settings); - _socketTimeout = TimeSpan.FromSeconds(_settings.SocketTimeoutSeconds); - _logger = LogProvider.Logger(this); - _isRunning = false; - _isRunningLock = new object(); - _unitOfOrderLock = new object(); - _acceptedConnections = 0; - _identity = ""; - _unitOfOrders = new int[_settings.MaxUnitOfOrder]; - if (!string.IsNullOrEmpty(_settings.Identity)) - { - _identity = $"[{_settings.Identity}] "; - } - - _acceptPool = new ConcurrentStack(); - _receivePool = new ConcurrentStack(); - _sendPool = new ConcurrentStack(); - - _maxNumberAccepts = new SemaphoreSlim(NumAccepts, NumAccepts); - _maxNumberAcceptedClients = new SemaphoreSlim(_settings.MaxConnections, _settings.MaxConnections); - _maxNumberSendOperations = new SemaphoreSlim(_settings.NumSimultaneouslyWriteOperations, - _settings.NumSimultaneouslyWriteOperations); - - int bufferSize = _settings.BufferSize * _settings.MaxConnections + - _settings.BufferSize * _settings.NumSimultaneouslyWriteOperations; - - _buffer = new byte[bufferSize]; - int bufferOffset = 0; - for (int i = 0; i < _settings.MaxConnections; i++) - { - SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); - readEventArgs.Completed += Receive_Completed; - readEventArgs.SetBuffer(_buffer, bufferOffset, _settings.BufferSize); - _receivePool.Push(readEventArgs); - bufferOffset += _settings.BufferSize; - } - - for (int i = 0; i < _settings.NumSimultaneouslyWriteOperations; i++) - { - SocketAsyncEventArgs writeEventArgs = new SocketAsyncEventArgs(); - writeEventArgs.Completed += Send_Completed; - writeEventArgs.UserToken = new AsyncEventToken(); - writeEventArgs.SetBuffer(_buffer, bufferOffset, _settings.BufferSize); - _sendPool.Push(writeEventArgs); - bufferOffset += _settings.BufferSize; - } - - for (int i = 0; i < NumAccepts; i++) - { - SocketAsyncEventArgs acceptEventArgs = new SocketAsyncEventArgs(); - acceptEventArgs.Completed += Accept_Completed; - _acceptPool.Push(acceptEventArgs); - } - } - - public AsyncEventServer(IPAddress ipAddress, ushort port, IConsumer consumer) - : this(ipAddress, port, consumer, new AsyncEventSettings()) - { - } - - public override void Send(ITcpSocket socket, byte[] data) - { - if (socket == null) - { - _logger.Error($"{_identity}called send with null-socket"); - return; - } - - if (!(socket is AsyncEventClient client)) - { - _logger.Error($"{_identity}called send with wrong instance"); - return; - } - - Send(client, data); - } - - public void Send(AsyncEventClient client, byte[] data) - { - _maxNumberSendOperations.Wait(); - if (!_isRunning) - { - _logger.Debug($"{_identity}Server stopped, not sending anymore."); - _maxNumberSendOperations.Release(); - return; - } - - if (!client.IsAlive) - { - _maxNumberSendOperations.Release(); - return; - } - - if (!client.Socket.Connected) - { - _logger.Error( - $"{_identity}AsyncEventClient not connected during send, closing socket. ({client.Identity})"); - client.Close(); - _maxNumberSendOperations.Release(); - return; - } - - if (!_sendPool.TryPop(out SocketAsyncEventArgs writeEventArgs)) - { - _logger.Error( - $"{_identity}Could not acquire writeEventArgs, closing socket. ({client.Identity})"); - client.Close(); - _maxNumberSendOperations.Release(); - return; - } - - AsyncEventToken token = (AsyncEventToken) writeEventArgs.UserToken; - token.Assign(client, data); - StartSend(writeEventArgs); - } - - internal void NotifyDisconnected(AsyncEventClient client) - { - if (client.ReadEventArgs == null) - { - _logger.Error($"{_identity}Already returned AsyncEventArgs to poll ({client.Identity})"); - return; - } - - FreeUnitOfOrder(client.UnitOfOrder); - ReleaseAccept(client.ReadEventArgs); - if (!_clients.Remove(client)) - { - _logger.Error($"{_identity}Could not remove client from list. ({client.Identity})"); - } - - _logger.Debug($"{_identity}Free Receive: {_maxNumberAcceptedClients.CurrentCount}"); - _logger.Debug($"{_identity}Free Send: {_maxNumberSendOperations.CurrentCount}"); - _logger.Debug($"{_identity}NotifyDisconnected::Current Connections: {_clients.Count}"); - try - { - OnClientDisconnected(client); - } - catch (Exception ex) - { - _logger.Error($"{_identity}Error during OnClientDisconnected() user code ({client.Identity})"); - _logger.Exception(ex); - } - } - - protected override void OnStart() - { - lock (_isRunningLock) - { - if (_isRunning) - { - _logger.Error($"{_identity}Error: Server already running."); - return; - } - - _acceptedConnections = 0; - _cancellation = new CancellationTokenSource(); - _clients.Clear(); - - lock (_unitOfOrderLock) - { - for (int i = 0; i < _unitOfOrders.Length; i++) - { - _unitOfOrders[i] = 0; - } - } - - _isRunning = true; - _serverThread = new Thread(Run); - _serverThread.Name = $"{_identity}{ServerThreadName}"; - _serverThread.IsBackground = true; - _serverThread.Start(); - } - } - - protected override void OnStop() - { - lock (_isRunningLock) - { - if (!_isRunning) - { - _logger.Error($"{_identity}Error: Server already stopped."); - return; - } - - _isRunning = false; - _cancellation.Cancel(); - Service.JoinThread(_serverThread, ThreadTimeoutMs, _logger); - Service.JoinThread(_timeoutThread, ThreadTimeoutMs, _logger); - if (_listenSocket != null) - { - _listenSocket.Close(); - } - - List clients = _clients.Snapshot(); - foreach (AsyncEventClient client in clients) - { - if (client == null) - { - continue; - } - - client.Close(); - } - - try - { - OnStopped(); - } - catch (Exception ex) - { - _logger.Error($"{_identity}Error during OnStopped() user code"); - _logger.Exception(ex); - } - } - } - - private int ClaimUnitOfOrder() - { - lock (_unitOfOrderLock) - { - int minNumber = int.MaxValue; - int unitOfOrder = 0; - for (int i = 0; i < _unitOfOrders.Length; i++) - { - if (_unitOfOrders[i] < minNumber) - { - minNumber = _unitOfOrders[i]; - unitOfOrder = i; - } - } - - _unitOfOrders[unitOfOrder]++; - return unitOfOrder; - } - } - - private void FreeUnitOfOrder(int unitOfOrder) - { - lock (_unitOfOrderLock) - { - _unitOfOrders[unitOfOrder]--; - } - } - - private void Run() - { - if (_isRunning && Startup()) - { - try - { - OnStarted(); - } - catch (Exception ex) - { - _logger.Error($"{_identity}Error during OnStarted() user code"); - _logger.Exception(ex); - } - - if (_socketTimeout.TotalSeconds > 0) - { - _timeoutThread = new Thread(CheckSocketTimeout); - _timeoutThread.Name = $"{_identity}{TimeoutThreadName}"; - _timeoutThread.IsBackground = true; - _timeoutThread.Start(); - } - - StartAccept(); - } - else - { - _logger.Error($"{_identity}Stopping server due to startup failure..."); - Stop(); - } - } - - private bool Startup() - { - IPEndPoint localEndPoint = new IPEndPoint(IpAddress, Port); - _listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - _settings.SocketSettings.ConfigureSocket(_listenSocket, _logger); - bool success = false; - int retries = 0; - while (_isRunning && !success && _settings.Retries >= retries) - { - try - { - _listenSocket.Bind(localEndPoint); - _listenSocket.Listen(_settings.SocketSettings.Backlog); - success = true; - } - catch (Exception exception) - { - _logger.Exception(exception); - if (exception is SocketException socketException && - socketException.SocketErrorCode == SocketError.AddressAlreadyInUse) - { - _logger.Error( - $"{_identity}Address is already in use ({IpAddress}:{Port}), try another IP/Port"); - } - - _logger.Error($"{_identity}Retrying in 1 Minute"); - Thread.Sleep(TimeSpan.FromMinutes(1)); - retries++; - } - } - - _logger.Info($"{_identity}Startup Result: {success}"); - return success; - } - - private void StartAccept() - { - _maxNumberAcceptedClients.Wait(); - _maxNumberAccepts.Wait(); - - if (!_isRunning) - { - _logger.Debug($"{_identity}Server stopped, not accepting new connections anymore."); - _maxNumberAccepts.Release(); - _maxNumberAcceptedClients.Release(); - return; - } - - if (!_acceptPool.TryPop(out SocketAsyncEventArgs acceptEventArgs)) - { - _logger.Error($"{_identity}Could not acquire acceptEventArgs."); - _maxNumberAccepts.Release(); - _maxNumberAcceptedClients.Release(); - return; - } - - bool willRaiseEvent = _listenSocket.AcceptAsync(acceptEventArgs); - if (!willRaiseEvent) - { - ProcessAccept(acceptEventArgs); - } - } - - private void Accept_Completed(object sender, SocketAsyncEventArgs acceptEventArg) - { - ProcessAccept(acceptEventArg); - } - - private void ProcessAccept(SocketAsyncEventArgs acceptEventArg) - { - Socket acceptSocket = acceptEventArg.AcceptSocket; - SocketError socketError = acceptEventArg.SocketError; - acceptEventArg.AcceptSocket = null; - _acceptPool.Push(acceptEventArg); - _maxNumberAccepts.Release(); - StartAccept(); - - if (socketError == SocketError.Success) - { - if (!_receivePool.TryPop(out SocketAsyncEventArgs readEventArgs)) - { - _logger.Error($"{_identity}Could not acquire readEventArgs"); - _maxNumberAcceptedClients.Release(); - return; - } - - int unitOfOrder = ClaimUnitOfOrder(); - _logger.Debug($"{_identity}ProcessAccept::Claimed UnitOfOrder: {unitOfOrder}"); - AsyncEventClient client = new AsyncEventClient( - acceptSocket, - readEventArgs, - this, - unitOfOrder - ); - _clients.Add(client); - readEventArgs.UserToken = client; - Interlocked.Increment(ref _acceptedConnections); - _logger.Debug($"{_identity}ProcessAccept::Current Connections: {_clients.Count}"); - _logger.Debug($"{_identity}Accepted Connections: {_acceptedConnections}"); - try - { - OnClientConnected(client); - } - catch (Exception ex) - { - _logger.Error($"{_identity}Error during OnClientConnected() user code ({client.Identity})"); - _logger.Exception(ex); - } - - StartReceive(readEventArgs); - } - else - { - if (socketError == SocketError.OperationAborted) - { - _logger.Info($"{_identity}Accept Socket aborted"); - } - else - { - _logger.Error($"{_identity}Accept Socket Error: {socketError}"); - } - - _maxNumberAcceptedClients.Release(); - } - } - - private void StartReceive(SocketAsyncEventArgs readEventArgs) - { - AsyncEventClient client = (AsyncEventClient) readEventArgs.UserToken; - if (client == null) - { - _logger.Error($"{_identity}StartReceive - Client is null"); - return; - } - - bool willRaiseEvent; - try - { - willRaiseEvent = client.Socket.ReceiveAsync(readEventArgs); - } - catch (ObjectDisposedException) - { - client.Close(); - return; - } - catch (InvalidOperationException) - { - _logger.Error($"{_identity}Error during StartReceive: InvalidOperationException ({client.Identity})"); - StartReceive(readEventArgs); - return; - } - - if (!willRaiseEvent) - { - ProcessReceive(readEventArgs); - } - } - - private void Receive_Completed(object sender, SocketAsyncEventArgs readEventArgs) - { - ProcessReceive(readEventArgs); - } - - private void ProcessReceive(SocketAsyncEventArgs readEventArgs) - { - AsyncEventClient client = (AsyncEventClient) readEventArgs.UserToken; - if (client == null) - { - _logger.Error($"{_identity}ProcessReceive - Client is null"); - return; - } - - if (readEventArgs.BytesTransferred > 0 && readEventArgs.SocketError == SocketError.Success) - { - byte[] data = new byte[readEventArgs.BytesTransferred]; - Buffer.BlockCopy(readEventArgs.Buffer, readEventArgs.Offset, data, 0, readEventArgs.BytesTransferred); - client.LastActive = DateTime.Now; - try - { - OnReceivedData(client, data); - } - catch (Exception ex) - { - _logger.Error($"{_identity}Error during OnReceivedData() user code ({client.Identity})"); - _logger.Exception(ex); - } - - StartReceive(readEventArgs); - } - else - { - client.Close(); - } - } - - private void StartSend(SocketAsyncEventArgs writeEventArgs) - { - AsyncEventToken token = (AsyncEventToken) writeEventArgs.UserToken; - if (token.OutstandingCount <= _settings.BufferSize) - { - writeEventArgs.SetBuffer(writeEventArgs.Offset, token.OutstandingCount); - Buffer.BlockCopy(token.Data, token.TransferredCount, writeEventArgs.Buffer, writeEventArgs.Offset, - token.OutstandingCount); - } - else - { - writeEventArgs.SetBuffer(writeEventArgs.Offset, _settings.BufferSize); - Buffer.BlockCopy(token.Data, token.TransferredCount, writeEventArgs.Buffer, writeEventArgs.Offset, - _settings.BufferSize); - } - - bool willRaiseEvent; - try - { - willRaiseEvent = token.Client.Socket.SendAsync(writeEventArgs); - } - catch (ObjectDisposedException) - { - token.Client.Close(); - ReleaseWrite(writeEventArgs); - return; - } - catch (InvalidOperationException) - { - _logger.Error( - $"{_identity}Error during StartSend: InvalidOperationException ({token.Client.Identity})"); - token.Client.Close(); - ReleaseWrite(writeEventArgs); - return; - } - - if (!willRaiseEvent) - { - ProcessSend(writeEventArgs); - } - } - - private void Send_Completed(object sender, SocketAsyncEventArgs writeEventArgs) - { - ProcessSend(writeEventArgs); - } - - private void ProcessSend(SocketAsyncEventArgs writeEventArgs) - { - AsyncEventToken token = (AsyncEventToken) writeEventArgs.UserToken; - if (writeEventArgs.SocketError == SocketError.Success) - { - token.Update(writeEventArgs.BytesTransferred); - if (token.OutstandingCount == 0) - { - token.Client.LastActive = DateTime.Now; - ReleaseWrite(writeEventArgs); - } - else - { - StartSend(writeEventArgs); - } - } - else - { - token.Client.Close(); - ReleaseWrite(writeEventArgs); - } - } - - private void ReleaseWrite(SocketAsyncEventArgs writeEventArgs) - { - AsyncEventToken token = (AsyncEventToken) writeEventArgs.UserToken; - token.Reset(); - _sendPool.Push(writeEventArgs); - _maxNumberSendOperations.Release(); - } - - private void ReleaseAccept(SocketAsyncEventArgs readEventArgs) - { - _receivePool.Push(readEventArgs); - readEventArgs.UserToken = null; - _maxNumberAcceptedClients.Release(); - } - - private void CheckSocketTimeout() - { - CancellationToken cancellationToken = _cancellation.Token; - while (_isRunning) - { - DateTime now = DateTime.Now; - List clients = _clients.Snapshot(); - foreach (AsyncEventClient client in clients) - { - if (client == null) - { - continue; - } - - TimeSpan lastOp = now - client.LastActive; - if (lastOp > _socketTimeout) - { - _logger.Error( - $"{_identity}Client socket timed out after {lastOp.TotalSeconds} seconds. SocketTimeout: {_socketTimeout.TotalSeconds} LastActive: {client.LastActive:yyyy-MM-dd HH:mm:ss} ({client.Identity})"); - client.Close(); - } - } - - // TODO next check based on longest lastActive (nextCheck = _socketTimeout - client.LastActive) - cancellationToken.WaitHandle.WaitOne((int) _socketTimeout.TotalMilliseconds / 2); - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventSettings.cs b/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventSettings.cs deleted file mode 100644 index 02bccb1..0000000 --- a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventSettings.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -using System; -using System.Runtime.Serialization; - -namespace Arrowgene.Services.Networking.Tcp.Server.AsyncEvent -{ - [DataContract] - public class AsyncEventSettings : ICloneable - { - [DataMember(Order = 0)] public string Identity { get; set; } - - [DataMember(Order = 1)] public int MaxConnections { get; set; } - - [DataMember(Order = 2)] public int NumSimultaneouslyWriteOperations { get; set; } - - [DataMember(Order = 3)] public int BufferSize { get; set; } - - [DataMember(Order = 4)] public int Retries { get; set; } - - [DataMember(Order = 5)] public int MaxUnitOfOrder { get; set; } - - [DataMember(Order = 9)] public int SocketTimeoutSeconds { get; set; } - - [DataMember(Order = 10)] public SocketSettings SocketSettings { get; set; } - - public AsyncEventSettings() - { - BufferSize = 2000; - MaxConnections = 100; - NumSimultaneouslyWriteOperations = 100; - Retries = 10; - SocketSettings = new SocketSettings(); - Identity = ""; - MaxUnitOfOrder = 1; - SocketTimeoutSeconds = -1; - } - - public AsyncEventSettings(AsyncEventSettings settings) - { - Identity = settings.Identity; - BufferSize = settings.BufferSize; - MaxConnections = settings.MaxConnections; - NumSimultaneouslyWriteOperations = settings.NumSimultaneouslyWriteOperations; - Retries = settings.Retries; - SocketSettings = new SocketSettings(settings.SocketSettings); - MaxUnitOfOrder = settings.MaxUnitOfOrder; - SocketTimeoutSeconds = settings.SocketTimeoutSeconds; - } - - public object Clone() - { - return new AsyncEventSettings(this); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventToken.cs b/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventToken.cs deleted file mode 100644 index 0baf453..0000000 --- a/Arrowgene.Services/Networking/Tcp/Server/AsyncEvent/AsyncEventToken.cs +++ /dev/null @@ -1,57 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -namespace Arrowgene.Services.Networking.Tcp.Server.AsyncEvent -{ - public class AsyncEventToken - { - public byte[] Data { get; private set; } - public AsyncEventClient Client { get; private set; } - public int TransferredCount { get; private set; } - public int OutstandingCount { get; private set; } - - public void Assign(AsyncEventClient client, byte[] data) - { - Client = client; - Data = data; - OutstandingCount = data.Length; - TransferredCount = 0; - } - - public void Update(int transferredCount) - { - TransferredCount += transferredCount; - OutstandingCount -= transferredCount; - } - - public void Reset() - { - Client = null; - Data = null; - OutstandingCount = 0; - TransferredCount = 0; - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Server/ITcpServer.cs b/Arrowgene.Services/Networking/Tcp/Server/ITcpServer.cs deleted file mode 100644 index dc9fb68..0000000 --- a/Arrowgene.Services/Networking/Tcp/Server/ITcpServer.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System.Net; - -namespace Arrowgene.Services.Networking.Tcp.Server -{ - public interface ITcpServer - { - IPAddress IpAddress { get; } - ushort Port { get; } - void Start(); - void Stop(); - void Send(ITcpSocket socket, byte[] data); - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Tcp/Server/TcpServer.cs b/Arrowgene.Services/Networking/Tcp/Server/TcpServer.cs deleted file mode 100644 index 56c9498..0000000 --- a/Arrowgene.Services/Networking/Tcp/Server/TcpServer.cs +++ /dev/null @@ -1,93 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System.Net; -using Arrowgene.Services.Exceptions; -using Arrowgene.Services.Networking.Tcp.Consumer; - -namespace Arrowgene.Services.Networking.Tcp.Server -{ - public abstract class TcpServer : ITcpServer - { - private readonly IConsumer _consumer; - - protected TcpServer(IPAddress ipAddress, ushort port, IConsumer consumer) - { - if (ipAddress == null) - throw new InvalidParameterException("IPAddress is null"); - - if (port <= 0 || port > 65535) - throw new InvalidParameterException($"Port({port}) invalid"); - - IpAddress = ipAddress; - Port = port; - _consumer = consumer; - } - - public IPAddress IpAddress { get; } - public ushort Port { get; } - - protected abstract void OnStart(); - protected abstract void OnStop(); - public abstract void Send(ITcpSocket socket, byte[] data); - - protected void OnReceivedData(ITcpSocket socket, byte[] data) - { - _consumer.OnReceivedData(socket, data); - } - - protected void OnClientDisconnected(ITcpSocket socket) - { - _consumer.OnClientDisconnected(socket); - } - - protected void OnClientConnected(ITcpSocket socket) - { - _consumer.OnClientConnected(socket); - } - - protected void OnStarted() - { - _consumer.OnStarted(); - } - - protected void OnStopped() - { - _consumer.OnStopped(); - } - - public void Start() - { - _consumer.OnStart(); - OnStart(); - } - - public void Stop() - { - _consumer.OnStop(); - OnStop(); - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Udp/ReceivedUdpPacketEventArgs.cs b/Arrowgene.Services/Networking/Udp/ReceivedUdpPacketEventArgs.cs deleted file mode 100644 index b247123..0000000 --- a/Arrowgene.Services/Networking/Udp/ReceivedUdpPacketEventArgs.cs +++ /dev/null @@ -1,47 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -// ReSharper disable MemberCanBePrivate.Global -// ReSharper disable UnusedAutoPropertyAccessor.Global - -using System; -using System.Net; - -namespace Arrowgene.Services.Networking.Udp -{ - public class ReceivedUdpPacketEventArgs : EventArgs - { - public ReceivedUdpPacketEventArgs(int size, byte[] received, IPEndPoint remoteIpEndPoint) - { - Size = size; - Received = received; - RemoteIpEndPoint = remoteIpEndPoint; - } - - public IPEndPoint RemoteIpEndPoint { get; } - public byte[] Received { get; } - public int Size { get; } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Networking/Udp/UdpSocket.cs b/Arrowgene.Services/Networking/Udp/UdpSocket.cs deleted file mode 100644 index fe7f90f..0000000 --- a/Arrowgene.Services/Networking/Udp/UdpSocket.cs +++ /dev/null @@ -1,221 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 Sebastian Heinz - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - -using System; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using Arrowgene.Services.Buffers; - -namespace Arrowgene.Services.Networking.Udp -{ - /// - /// Class for handling udp sending and receiving of packets. - /// Call before sending any data, to be able to receive a response. - /// If you act as a server with , there is no need to call - /// - public class UdpSocket - { - /// - /// Defines the maximum size to be received or send, - /// drops requests exceeding limit. - /// - public const int DefaultMaxPayloadSizeBytes = 384; - - public int MaxPayloadSizeBytes { get; set; } - - private readonly Socket _socket; - private readonly byte[] _buffer; - private Thread _udpThread; - private bool _receive; - private bool _isBound; - - - /// - /// Creates a new instance of - /// - public UdpSocket() : this (DefaultMaxPayloadSizeBytes) - { - } - - public UdpSocket(int maxPayloadSizeBytes) - { - MaxPayloadSizeBytes = maxPayloadSizeBytes; - _isBound = false; - _receive = false; - _buffer = new byte[MaxPayloadSizeBytes]; - _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - } - - /// - /// Occurs when data is received - /// - public event EventHandler ReceivedPacket; - - /// - /// Listen for incomming data and start receiving - /// - /// - public void StartListen(IPEndPoint remoteEp) - { - if (!_isBound) - { - _socket.Bind(remoteEp); - _isBound = true; - } - - StartReceive(); - } - - /// - /// Send data to an destination - /// - /// - /// - public void Send(byte[] buffer, EndPoint remoteEp) - { - SendTo(buffer, remoteEp); - } - - /// - /// Send data as broadcast. - /// - /// - /// - public void SendBroadcast(byte[] buffer, ushort port) - { - SendToBroadcast(buffer, port); - } - - /// - /// Starts receiving data - /// - public void StartReceive() - { - StartReceiveThread(); - } - - /// - /// Stops receiving any data - /// - public void StopReceive() - { - _receive = false; - - if (_udpThread != null) - { - if (Thread.CurrentThread != _udpThread) - { - const int waitTimeout = 1000; - - if (_udpThread.Join(waitTimeout)) - { - Debug.WriteLine("UDPBase::Stop: Udp thread ended clean."); - } - else - { - Debug.WriteLine( - $"UDPBase::Stop: Exceeded maximum timeout of {waitTimeout} ms, aborting thread..."); - _udpThread.Abort(); - } - } - else - { - Debug.WriteLine("UDPBase::Stop: Tried to join udp thread from within udp thread, letting udp thread run out.."); - } - } - } - - /// - /// Releases all ressources - /// - public void Dispose() - { - StopReceive(); - _socket.Close(); - } - - private void StartReceiveThread() - { - if (!_receive) - { - _receive = true; - _udpThread = new Thread(Receive); - _udpThread.Name = "UdpReceive"; - _udpThread.Start(); - } - } - - private void Receive() - { - while (_receive) - { - if (_socket.Poll(10, SelectMode.SelectRead)) - { - // Create EndPoint, Senders information will be written to object. - IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); - EndPoint senderRemote = sender; - - int read = _socket.ReceiveFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref senderRemote); - - IPEndPoint remoteIpEndPoint = (IPEndPoint) senderRemote; - - IBuffer received = new StreamBuffer(_buffer, 0, read); - OnReceivedUdpPacket(read, received.GetAllBytes(), remoteIpEndPoint); - } - } - } - - private void SendTo(byte[] buffer, EndPoint remoteEp) - { - if (buffer.Length <= MaxPayloadSizeBytes) - { - _socket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, remoteEp); - } - else - { - Debug.WriteLine($"UDPBase::SendTo: Exceeded maximum size of {MaxPayloadSizeBytes} byte"); - } - } - - private void SendToBroadcast(byte[] buffer, ushort port) - { - _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); - _socket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port)); - _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false); - } - - private void OnReceivedUdpPacket(int receivedBytesCount, byte[] received, IPEndPoint remoteIpEndPoint) - { - EventHandler receivedBroadcast = ReceivedPacket; - if (receivedBroadcast != null) - { - ReceivedUdpPacketEventArgs receivedProxyPacketEventArgs = new ReceivedUdpPacketEventArgs(receivedBytesCount, received, remoteIpEndPoint); - receivedBroadcast(this, receivedProxyPacketEventArgs); - } - } - } -} \ No newline at end of file diff --git a/Arrowgene.Services/Performance/PerformanceMonitor.cs b/Arrowgene.Services/Performance/PerformanceMonitor.cs index c4df977..7af9021 100644 --- a/Arrowgene.Services/Performance/PerformanceMonitor.cs +++ b/Arrowgene.Services/Performance/PerformanceMonitor.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using Arrowgene.Services.Logging; +using Arrowgene.Logging; namespace Arrowgene.Services.Performance { diff --git a/Arrowgene.Services/Service.cs b/Arrowgene.Services/Service.cs index 95a1bd4..e68641c 100644 --- a/Arrowgene.Services/Service.cs +++ b/Arrowgene.Services/Service.cs @@ -1,7 +1,7 @@ using System; using System.Text; using System.Threading; -using Arrowgene.Services.Logging; +using Arrowgene.Logging; namespace Arrowgene.Services { diff --git a/Arrowgene.Services/Tasks/PeriodicTask.cs b/Arrowgene.Services/Tasks/PeriodicTask.cs index c48b24f..f3a9c62 100644 --- a/Arrowgene.Services/Tasks/PeriodicTask.cs +++ b/Arrowgene.Services/Tasks/PeriodicTask.cs @@ -1,7 +1,7 @@ using System; using System.Threading; using System.Threading.Tasks; -using Arrowgene.Services.Logging; +using Arrowgene.Logging; namespace Arrowgene.Services.Tasks { diff --git a/README.md b/README.md index ccba45d..133e53e 100644 --- a/README.md +++ b/README.md @@ -39,45 +39,13 @@ These are the main Interfaces and building blocks. A default implementation for each part is provided, which will allow a quick start, so that the focus can be on the business logic instead of writing boiler plate code. -## Pipeline +## Components -This is an overview of the default pipeline that describes how data is send, received and handled. -It is not necessary to use the library on both ends, -it can be used for the server side only or as a client to connect to a remote host. -``` - @@@@@ - @@@@@ @@@@@ - ┌───────────────────────────────┐ @@@@@ @@@@@ @@@@@ - ==|data|==>@ [IClient/IServer] ==|data|==> @══════╗@@@ @@@@@ - └───────────────────────────────┘ @@@║@ @@@@@ @@@@@ - @@@@ ║ Internet @@@@@ - ┌─────────────┐ ┌───────────────────────────────┐ @@@@║@ @@@@@ - │ [IConsumer] @<==|data|==@ [IClient/IServer] <==|data|== @══════╝@@ @@@@@ @@@@@ @@@@@ - └─────────────┘ └───────────────────────────────┘ @@@@@ @@@@@ @@@@@ - @@@@@ @@@@@ - @@@@@ -``` - -## Project - -### [Buffers](./Arrowgene.Services/Buffers) -Methods to read from a byte array. - -### [Logging](./Arrowgene.Services/Logging) -Provides logging with different log levels. - -### [Networking](./Arrowgene.Services/Networking) -Sever and client implementations to handle network traffic. +Each component is also available individually: -### [Tcp/Consumer](./Arrowgene.Services/Networking/Tcp/Consumer) -Reading and writing data. - -- [Messages](./Arrowgene.Services/Networking/Tcp/Consumer/Messages) -Provides methods to serialize and deserialize messages and -calls handler methods for registered handlers. -The server and client need to use the same assembly, -so it is recommended to create your model classes in a shared library (.dll). -Model classes need to be marked with [Serializable]. +- https://github.com/sebastian-heinz/Arrowgene.Logging +- https://github.com/sebastian-heinz/Arrowgene.Buffers +- https://github.com/sebastian-heinz/Arrowgene.Networking ## Links diff --git a/package.json b/package.json deleted file mode 100644 index 0150b24..0000000 --- a/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "net.arrowgene.services", - "displayName": "Arrowgene.Services", - "description": "Network Library", - "version": "1.13.2", - "unity": "2019.2", - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/sebastian-heinz/Arrowgene.Services.git" - }, - "author": "sebastian-heinz (https://github.com/sebastian-heinz)", - "dependencies": {} -} \ No newline at end of file diff --git a/release-pp.sh b/release-pp.sh deleted file mode 100755 index 0a66c57..0000000 --- a/release-pp.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish?tabs=netcore2x -VERSION=1 -mkdir ./release -for RUNTIME in win-x86 win-x64 linux-x64 osx-x64; do - # Server - dotnet publish Arrowgene.Services.PingPong/Arrowgene.Services.PingPong.csproj --self-contained true /p:PublishSingleFile=true /p:PublishTrimmed=true /p:Version=$VERSION --runtime $RUNTIME --configuration Release --output ./publish/$RUNTIME-$VERSION/ - # Pack - tar cjf ./release/$RUNTIME-$VERSION.tar.gz ./publish/$RUNTIME-$VERSION -done \ No newline at end of file diff --git a/services.version b/services.version deleted file mode 100644 index 11d0d97..0000000 --- a/services.version +++ /dev/null @@ -1 +0,0 @@ -1.13.4 \ No newline at end of file