Files
PipeMethodCallsDemo/PipeClient/Program.cs
T

190 lines
6.1 KiB
C#
Raw Normal View History

2026-11-10 11:06:10 +01:00
using PipeMethodCalls;
using PipeShared;
2026-11-10 10:38:20 +01:00
using System.Diagnostics;
using System.Xml.Linq;
2026-11-10 09:23:35 +01:00
2026-11-10 10:20:18 +01:00
// All output is written to an XML report next to the executable
string reportPath = Path.Combine(AppContext.BaseDirectory, "ClientReport.xml");
var report = new XElement("Report", new XAttribute("Started", DateTime.Now.ToString("O")));
2026-11-10 11:06:10 +01:00
bool colorSwitch = false;
2026-11-10 10:20:18 +01:00
Log("Client started.");
2026-11-10 09:23:35 +01:00
2026-11-10 10:16:24 +01:00
// Unique pipe name per client run, so multiple clients/servers do not interfere
string pipeName = $"PipeDemo-{Environment.ProcessId}-{Guid.NewGuid():N}";
2026-11-10 09:23:35 +01:00
Process? serverProcess = null;
2026-11-10 10:42:57 +01:00
PipeClient<IServerMethods> client = null!;
2026-11-10 09:23:35 +01:00
try
{
2026-11-10 10:20:18 +01:00
Log($"Starting server on pipe {pipeName}...");
2026-11-10 10:16:24 +01:00
await StartServerAndConnectAsync(pipeName);
2026-11-10 10:20:18 +01:00
Log("Connected to server.");
2026-11-10 10:16:24 +01:00
await BasicCallsExampleAsync();
await ServerExceptionsExampleAsync();
await CancellationExampleAsync();
await KillOnTimeoutExampleAsync();
await CrashExampleAsync();
}
catch (Exception ex) when (ex is not PipeInvokeFailedException)
{
// Communication failed: check whether the server process died
if (serverProcess is not null && serverProcess.WaitForExit(2000))
2026-11-10 10:20:18 +01:00
Log($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}");
2026-11-10 10:16:24 +01:00
else
2026-11-10 10:20:18 +01:00
Log($"Communication error: {ex.GetType().Name}: {ex.Message}");
2026-11-10 10:16:24 +01:00
}
finally
{
// Disposing the client closes the pipe, the server then exits.
client?.Dispose();
if (serverProcess is not null)
2026-11-10 09:23:35 +01:00
{
2026-11-10 10:16:24 +01:00
if (!serverProcess.WaitForExit(5000))
serverProcess.Kill();
serverProcess.Dispose();
2026-11-10 09:23:35 +01:00
}
2026-11-10 10:16:24 +01:00
}
2026-11-10 10:20:18 +01:00
Log("Client finished.");
lock (report)
new XDocument(report).Save(reportPath);
// Thread-safe: also called from the Process.Exited event
2026-11-10 11:06:10 +01:00
2026-11-10 10:20:18 +01:00
void Log(string message)
{
lock (report)
report.Add(new XElement("Entry", new XAttribute("Time", DateTime.Now.ToString("O")), message));
2026-11-10 11:06:10 +01:00
if (message.Contains("Server exception"))
{
Console.ForegroundColor = colorSwitch ? ConsoleColor.DarkRed : ConsoleColor.Red;
colorSwitch = !colorSwitch;
}
else
Console.ForegroundColor = ConsoleColor.Green;
2026-11-10 10:38:20 +01:00
Console.WriteLine(message);
Console.ResetColor();
2026-11-10 10:20:18 +01:00
}
2026-11-10 09:23:35 +01:00
2026-11-10 10:16:24 +01:00
async Task BasicCallsExampleAsync()
{
2026-11-10 09:23:35 +01:00
int sum = await client.InvokeAsync(c => c.Add(2, 3));
2026-11-10 10:20:18 +01:00
Log($"Add(2, 3) = {sum}");
2026-11-10 09:23:35 +01:00
var vector = await client.InvokeAsync(c => c.AddVector(new System.Numerics.Vector3(1, 2, 3), new System.Numerics.Vector3(4, 5, 6)));
2026-11-10 10:20:18 +01:00
Log($"AddVector((1,2,3), (4,5,6)) = {vector}");
2026-11-10 09:23:35 +01:00
double quotient = await client.InvokeAsync(c => c.Divide(10, 4));
2026-11-10 10:20:18 +01:00
Log($"Divide(10, 4) = {quotient}");
2026-11-10 09:23:35 +01:00
string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
2026-11-10 10:20:18 +01:00
Log(echo);
2026-11-10 10:16:24 +01:00
}
2026-11-10 09:23:35 +01:00
2026-11-10 10:16:24 +01:00
// Server-side exceptions are forwarded to the client
async Task ServerExceptionsExampleAsync()
{
2026-11-10 09:23:35 +01:00
try
{
await client.InvokeAsync(c => c.Divide(1, 0));
}
catch (PipeInvokeFailedException ex)
{
2026-11-10 10:20:18 +01:00
Log($"Server exception (Divide): {ex.Message}");
2026-11-10 09:23:35 +01:00
}
try
{
await client.InvokeAsync(c => c.EchoAsync(""));
}
catch (PipeInvokeFailedException ex)
{
2026-11-10 10:20:18 +01:00
Log($"Server exception (Echo): {ex.Message}");
2026-11-10 09:23:35 +01:00
}
}
2026-11-10 10:16:24 +01:00
// InvokeAsync with a CancellationToken: the client stops waiting when the token is canceled.
// PipeMethodCalls does not propagate cancellation to the server, so an explicit
// CancelOperation call with the operation id stops the server-side work as well.
async Task CancellationExampleAsync()
2026-11-10 09:23:35 +01:00
{
2026-11-10 10:16:24 +01:00
using var invokeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
var operationId = Guid.NewGuid();
try
{
int result = await client.InvokeAsync(c => c.SlowOperationAsync(2000, operationId), invokeCts.Token);
2026-11-10 10:20:18 +01:00
Log($"SlowOperationAsync = {result}");
2026-11-10 10:16:24 +01:00
}
catch (OperationCanceledException)
{
await client.InvokeAsync(c => c.CancelOperation(operationId));
2026-11-10 10:20:18 +01:00
Log("SlowOperationAsync canceled after 200 ms.");
2026-11-10 10:16:24 +01:00
}
2026-11-10 09:23:35 +01:00
}
2026-11-10 10:16:24 +01:00
// Kill the server process if it does not respond in time, then restart it
async Task KillOnTimeoutExampleAsync()
2026-11-10 09:23:35 +01:00
{
2026-11-10 10:16:24 +01:00
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
try
2026-11-10 09:23:35 +01:00
{
2026-11-10 10:16:24 +01:00
await client.InvokeAsync(c => c.SlowOperationAsync(30_000, Guid.NewGuid()), timeoutCts.Token);
}
catch (OperationCanceledException) when (serverProcess is not null)
{
2026-11-10 10:20:18 +01:00
Log("Server did not respond within 1 s. Killing server process...");
2026-11-10 10:16:24 +01:00
serverProcess.Kill(entireProcessTree: true);
await serverProcess.WaitForExitAsync();
2026-11-10 09:23:35 +01:00
serverProcess.Dispose();
2026-11-10 10:16:24 +01:00
client.Dispose();
2026-11-10 10:20:18 +01:00
Log("Restarting server...");
2026-11-10 10:16:24 +01:00
await StartServerAndConnectAsync(pipeName);
2026-11-10 10:20:18 +01:00
Log("Reconnected to server.");
2026-11-10 09:23:35 +01:00
}
}
2026-11-10 10:16:24 +01:00
// Simulate a server crash
async Task CrashExampleAsync() => await client.InvokeAsync(c => c.Crash(42));
async Task StartServerAndConnectAsync(string pipeName)
{
var process = StartServer(pipeName);
process.EnableRaisingEvents = true;
process.Exited += (_, _) =>
{
if (process.ExitCode != 0)
2026-11-10 10:20:18 +01:00
Log($"Server process exited abnormally (exit code {process.ExitCode}).");
2026-11-10 10:16:24 +01:00
};
serverProcess = process;
2026-11-10 10:42:57 +01:00
client = new PipeClient<IServerMethods>(new JsonFieldsPipeSerializer(), pipeName);
2026-11-10 10:16:24 +01:00
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await client.ConnectAsync(cts.Token);
}
2026-11-10 09:23:35 +01:00
// 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() ? "PipeServer.exe" : "PipeServer");
2026-11-10 09:23:35 +01:00
ProcessStartInfo startInfo;
if (File.Exists(serverExe))
{
startInfo = new ProcessStartInfo(serverExe);
}
else
{
startInfo = new ProcessStartInfo("dotnet");
startInfo.ArgumentList.Add(Path.Combine(baseDir, "PipeServer.dll"));
2026-11-10 09:23:35 +01:00
}
startInfo.ArgumentList.Add($"{PipeConstants.PipeNameArgPrefix}{pipeName}");
startInfo.UseShellExecute = false;
return Process.Start(startInfo)
?? throw new InvalidOperationException("Server konnte nicht gestartet werden.");
}