From d14a20dfaca924196dbb2882784fa00ef2c182cc Mon Sep 17 00:00:00 2001 From: Matthias Heil Date: Tue, 10 Nov 2026 09:23:35 +0100 Subject: [PATCH] Initial commit --- Client/Client.csproj | 15 ++++ Client/Program.cs | 115 +++++++++++++++++++++++++++++ PipeDemo.slnx | 5 ++ Server/Calculator.cs | 28 +++++++ Server/Program.cs | 21 ++++++ Server/Server.csproj | 14 ++++ Shared/ICalculator.cs | 17 +++++ Shared/JsonFieldsPipeSerializer.cs | 16 ++++ Shared/Shared.csproj | 13 ++++ 9 files changed, 244 insertions(+) create mode 100644 Client/Client.csproj create mode 100644 Client/Program.cs create mode 100644 PipeDemo.slnx create mode 100644 Server/Calculator.cs create mode 100644 Server/Program.cs create mode 100644 Server/Server.csproj create mode 100644 Shared/ICalculator.cs create mode 100644 Shared/JsonFieldsPipeSerializer.cs create mode 100644 Shared/Shared.csproj diff --git a/Client/Client.csproj b/Client/Client.csproj new file mode 100644 index 0000000..2723afa --- /dev/null +++ b/Client/Client.csproj @@ -0,0 +1,15 @@ + + + + + + + + + Exe + net10.0 + enable + enable + + + diff --git a/Client/Program.cs b/Client/Program.cs new file mode 100644 index 0000000..2121ca1 --- /dev/null +++ b/Client/Program.cs @@ -0,0 +1,115 @@ +using System.Diagnostics; +using PipeMethodCalls; +using Shared; + +Console.WriteLine("Client started."); + +const string pipeName = "PipeDemo"; + +Process? serverProcess = null; +PipeClient client = new(new JsonFieldsPipeSerializer(), pipeName); + +try +{ + // Check whether a server is already running by trying a short connect + try + { + using var probeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(500)); + await client.ConnectAsync(probeCts.Token); + Console.WriteLine("Server already running."); + } + catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) + { + client.Dispose(); + Console.WriteLine("No server running. Starting server..."); + serverProcess = StartServer(pipeName); + serverProcess.EnableRaisingEvents = true; + serverProcess.Exited += (_, _) => + { + if (serverProcess.ExitCode != 0) + Console.WriteLine($"Server process exited abnormally (exit code {serverProcess.ExitCode})."); + }; + + client = new PipeClient(new JsonFieldsPipeSerializer(), pipeName); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await client.ConnectAsync(cts.Token); + } + Console.WriteLine("Connected to server."); + + int sum = await client.InvokeAsync(c => c.Add(2, 3)); + Console.WriteLine($"Add(2, 3) = {sum}"); + + var vector = await client.InvokeAsync(c => c.AddVector(new System.Numerics.Vector3(1, 2, 3), new System.Numerics.Vector3(4, 5, 6))); + Console.WriteLine($"AddVector((1,2,3), (4,5,6)) = {vector}"); + + double quotient = await client.InvokeAsync(c => c.Divide(10, 4)); + Console.WriteLine($"Divide(10, 4) = {quotient}"); + + string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo")); + Console.WriteLine(echo); + + // Server-side exceptions are forwarded to the client + try + { + await client.InvokeAsync(c => c.Divide(1, 0)); + } + catch (PipeInvokeFailedException ex) + { + Console.WriteLine($"Server exception (Divide): {ex.Message}"); + } + + try + { + await client.InvokeAsync(c => c.EchoAsync("")); + } + catch (PipeInvokeFailedException ex) + { + Console.WriteLine($"Server exception (Echo): {ex.Message}"); + } + + // Simulate a server crash + await client.InvokeAsync(c => c.Crash(42)); +} +catch (Exception ex) when (ex is not PipeInvokeFailedException) +{ + // Communication failed: check whether the server process died + if (serverProcess is not null && serverProcess.WaitForExit(2000)) + Console.WriteLine($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}"); + else + Console.WriteLine($"Communication error: {ex.GetType().Name}: {ex.Message}"); +} +finally +{ + // Disposing the client closes the pipe, the server then exits. + client.Dispose(); + if (serverProcess is not null) + { + if (!serverProcess.WaitForExit(5000)) + serverProcess.Kill(); + serverProcess.Dispose(); + } +} + +Console.WriteLine("Client finished."); + +// Start server process (Server is referenced, so its output is copied next to the client). +static Process StartServer(string pipeName) +{ + string baseDir = AppContext.BaseDirectory; + string serverExe = Path.Combine(baseDir, OperatingSystem.IsWindows() ? "Server.exe" : "Server"); + ProcessStartInfo startInfo; + if (File.Exists(serverExe)) + { + startInfo = new ProcessStartInfo(serverExe); + } + else + { + startInfo = new ProcessStartInfo("dotnet"); + startInfo.ArgumentList.Add(Path.Combine(baseDir, "Server.dll")); + } + startInfo.ArgumentList.Add($"{PipeConstants.PipeNameArgPrefix}{pipeName}"); + startInfo.UseShellExecute = false; + + return Process.Start(startInfo) + ?? throw new InvalidOperationException("Server konnte nicht gestartet werden."); +} diff --git a/PipeDemo.slnx b/PipeDemo.slnx new file mode 100644 index 0000000..e263b75 --- /dev/null +++ b/PipeDemo.slnx @@ -0,0 +1,5 @@ + + + + + diff --git a/Server/Calculator.cs b/Server/Calculator.cs new file mode 100644 index 0000000..d731ebf --- /dev/null +++ b/Server/Calculator.cs @@ -0,0 +1,28 @@ +using System.Numerics; +using Shared; + +namespace Server; + +public class Calculator : ICalculator +{ + public int Add(int a, int b) => a + b; + + public Vector3 AddVector(Vector3 a, Vector3 b) => a + b; + + public double Divide(double a, double b) + { + if (b == 0) + throw new DivideByZeroException("Division durch 0 ist nicht erlaubt."); + return a / b; + } + + public async Task EchoAsync(string text) + { + await Task.Delay(50); + if (string.IsNullOrEmpty(text)) + throw new ArgumentException("Text darf nicht leer sein.", nameof(text)); + return $"Echo: {text}"; + } + + public void Crash(int exitCode) => Environment.Exit(exitCode); +} diff --git a/Server/Program.cs b/Server/Program.cs new file mode 100644 index 0000000..6d60086 --- /dev/null +++ b/Server/Program.cs @@ -0,0 +1,21 @@ +using PipeMethodCalls; +using Server; +using Shared; + +string pipeName = args.FirstOrDefault(a => a.StartsWith(PipeConstants.PipeNameArgPrefix))? +[PipeConstants.PipeNameArgPrefix.Length..] ?? "PipeDemo"; + +Console.WriteLine($"Server started. Pipe: {pipeName}"); + +// Exceptions in handler methods are caught by PipeMethodCalls and sent to the client +// (client receives PipeInvokeFailedException with the server exception details). +var server = new PipeServer( + new JsonFieldsPipeSerializer(), + pipeName, + () => new Calculator()); + +await server.WaitForConnectionAsync(); +Console.WriteLine("Client connected."); + +await server.WaitForRemotePipeCloseAsync(); +Console.WriteLine("Client disconnected. Server exiting."); diff --git a/Server/Server.csproj b/Server/Server.csproj new file mode 100644 index 0000000..73d7a71 --- /dev/null +++ b/Server/Server.csproj @@ -0,0 +1,14 @@ + + + + + + + + Exe + net10.0 + enable + enable + + + diff --git a/Shared/ICalculator.cs b/Shared/ICalculator.cs new file mode 100644 index 0000000..4ada0d2 --- /dev/null +++ b/Shared/ICalculator.cs @@ -0,0 +1,17 @@ +using System.Numerics; + +namespace Shared; + +public interface ICalculator +{ + int Add(int a, int b); + Vector3 AddVector(Vector3 a, Vector3 b); + double Divide(double a, double b); + Task EchoAsync(string text); + void Crash(int exitCode); +} + +public static class PipeConstants +{ + public const string PipeNameArgPrefix = "--pipe="; +} diff --git a/Shared/JsonFieldsPipeSerializer.cs b/Shared/JsonFieldsPipeSerializer.cs new file mode 100644 index 0000000..7b50db7 --- /dev/null +++ b/Shared/JsonFieldsPipeSerializer.cs @@ -0,0 +1,16 @@ +using System.Text.Json; +using PipeMethodCalls; + +namespace Shared; + +/// +/// JSON serializer that also includes public fields (required for System.Numerics.Vector3). +/// +public class JsonFieldsPipeSerializer : IPipeSerializer +{ + private static readonly JsonSerializerOptions Options = new() { IncludeFields = true }; + + public object Deserialize(byte[] data, Type type) => JsonSerializer.Deserialize(data, type, Options)!; + + public byte[] Serialize(object o) => JsonSerializer.SerializeToUtf8Bytes(o, Options); +} diff --git a/Shared/Shared.csproj b/Shared/Shared.csproj new file mode 100644 index 0000000..d1db7d6 --- /dev/null +++ b/Shared/Shared.csproj @@ -0,0 +1,13 @@ + + + + net10.0 + enable + enable + + + + + + +