Files
PipeMethodCallsDemo/Client/Program.cs
T

165 lines
5.5 KiB
C#
Raw Normal View History

2026-11-10 10:16:24 +01:00
using System.Diagnostics;
2026-11-10 09:23:35 +01:00
using PipeMethodCalls;
using ClientServerShared;
2026-11-10 09:23:35 +01:00
Console.WriteLine("Client started.");
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:16:24 +01:00
PipeClient<ICalculator> client = null!;
2026-11-10 09:23:35 +01:00
try
{
2026-11-10 10:16:24 +01:00
Console.WriteLine($"Starting server on pipe {pipeName}...");
await StartServerAndConnectAsync(pipeName);
Console.WriteLine("Connected to server.");
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))
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)
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
}
Console.WriteLine("Client finished.");
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));
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);
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)
{
Console.WriteLine($"Server exception (Divide): {ex.Message}");
}
try
{
await client.InvokeAsync(c => c.EchoAsync(""));
}
catch (PipeInvokeFailedException ex)
{
Console.WriteLine($"Server exception (Echo): {ex.Message}");
}
}
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);
Console.WriteLine($"SlowOperationAsync = {result}");
}
catch (OperationCanceledException)
{
await client.InvokeAsync(c => c.CancelOperation(operationId));
Console.WriteLine("SlowOperationAsync canceled after 200 ms.");
}
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)
{
Console.WriteLine("Server did not respond within 1 s. Killing server process...");
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();
Console.WriteLine("Restarting server...");
await StartServerAndConnectAsync(pipeName);
Console.WriteLine("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)
Console.WriteLine($"Server process exited abnormally (exit code {process.ExitCode}).");
};
serverProcess = process;
client = new PipeClient<ICalculator>(new JsonFieldsPipeSerializer(), pipeName);
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() ? "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.");
}