Compare commits
4
Commits
3fe7fa42e5
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98bdb3cf0d | ||
|
|
b7ddb46ded | ||
|
|
beb7086867 | ||
|
|
e1acf71c5d |
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
################################################################################
|
################################################################################
|
||||||
# This .gitignore file was automatically created by Microsoft(R) Visual Studio.
|
# This .gitignore file was automatically created by Microsoft(R) Visual Studio.
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|
||||||
/.vs
|
/.vs
|
||||||
|
.idea
|
||||||
|
|||||||
+29
-80
@@ -1,57 +1,50 @@
|
|||||||
using PipeMethodCalls;
|
using PipeMethodCalls;
|
||||||
|
using PipeClient;
|
||||||
using PipeShared;
|
using PipeShared;
|
||||||
using System.Diagnostics;
|
|
||||||
using System.Xml.Linq;
|
using System.Xml.Linq;
|
||||||
|
|
||||||
// All output is written to an XML report next to the executable
|
// All output is written to an XML report next to the executable
|
||||||
string reportPath = Path.Combine(AppContext.BaseDirectory, "ClientReport.xml");
|
var reportPath = Path.Combine(AppContext.BaseDirectory, "ClientReport.xml");
|
||||||
var report = new XElement("Report", new XAttribute("Started", DateTime.Now.ToString("O")));
|
var report = new XElement("Report", new XAttribute("Started", DateTime.Now.ToString("O")));
|
||||||
bool colorSwitch = false;
|
var colorSwitch = false;
|
||||||
|
|
||||||
Log("Client started.");
|
Log("Client started.");
|
||||||
|
|
||||||
// Unique pipe name per client run, so multiple clients/servers do not interfere
|
// Unique pipe name per client run, so multiple clients/servers do not interfere
|
||||||
string pipeName = $"PipeDemo-{Environment.ProcessId}-{Guid.NewGuid():N}";
|
var pipeName = $"PipeDemo-{Environment.ProcessId}";
|
||||||
|
|
||||||
Process? serverProcess = null;
|
var server = new ServerConnection(pipeName, Log);
|
||||||
PipeClient<IServerMethods> client = null!;
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Log($"Starting server on pipe {pipeName}...");
|
Log($"Starting server on pipe {pipeName}...");
|
||||||
await StartServerAndConnectAsync(pipeName);
|
await server.StartAsync();
|
||||||
Log("Connected to server.");
|
Log("Connected to server.");
|
||||||
|
|
||||||
await BasicCallsExampleAsync();
|
await BasicCallsExampleAsync(server.Client);
|
||||||
await ServerExceptionsExampleAsync();
|
await ServerExceptionsExampleAsync(server.Client);
|
||||||
await CancellationExampleAsync();
|
await CancellationExampleAsync(server.Client);
|
||||||
await KillOnTimeoutExampleAsync();
|
await KillOnTimeoutExampleAsync(server);
|
||||||
await CrashExampleAsync();
|
await CrashExampleAsync(server.Client);
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is not PipeInvokeFailedException)
|
catch (Exception ex) when (ex is not PipeInvokeFailedException)
|
||||||
{
|
{
|
||||||
// Communication failed: check whether the server process died
|
// Communication failed: check whether the server process died
|
||||||
if (serverProcess is not null && serverProcess.WaitForExit(2000))
|
Log(server.WaitForServerExit(2000, out var exitCode)
|
||||||
Log($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}");
|
? $"Connection lost, server terminated with exit code {exitCode}: {ex.GetType().Name}: {ex.Message}"
|
||||||
else
|
: $"Communication error: {ex.GetType().Name}: {ex.Message}");
|
||||||
Log($"Communication error: {ex.GetType().Name}: {ex.Message}");
|
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
// Disposing the client closes the pipe, the server then exits.
|
server.Dispose();
|
||||||
client?.Dispose();
|
|
||||||
if (serverProcess is not null)
|
|
||||||
{
|
|
||||||
if (!serverProcess.WaitForExit(5000))
|
|
||||||
serverProcess.Kill();
|
|
||||||
serverProcess.Dispose();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Log("Client finished.");
|
Log("Client finished.");
|
||||||
lock (report)
|
lock (report)
|
||||||
new XDocument(report).Save(reportPath);
|
new XDocument(report).Save(reportPath);
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
// Thread-safe: also called from the Process.Exited event
|
// Thread-safe: also called from the Process.Exited event
|
||||||
|
|
||||||
void Log(string message)
|
void Log(string message)
|
||||||
@@ -69,23 +62,23 @@ void Log(string message)
|
|||||||
Console.ResetColor();
|
Console.ResetColor();
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task BasicCallsExampleAsync()
|
async Task BasicCallsExampleAsync(PipeClient<IPipeServerMethods> client)
|
||||||
{
|
{
|
||||||
int sum = await client.InvokeAsync(c => c.Add(2, 3));
|
var sum = await client.InvokeAsync(c => c.Add(2, 3));
|
||||||
Log($"Add(2, 3) = {sum}");
|
Log($"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)));
|
var vector = await client.InvokeAsync(c => c.AddVector(new System.Numerics.Vector3(1, 2, 3), new System.Numerics.Vector3(4, 5, 6)));
|
||||||
Log($"AddVector((1,2,3), (4,5,6)) = {vector}");
|
Log($"AddVector((1,2,3), (4,5,6)) = {vector}");
|
||||||
|
|
||||||
double quotient = await client.InvokeAsync(c => c.Divide(10, 4));
|
var quotient = await client.InvokeAsync(c => c.Divide(10, 4));
|
||||||
Log($"Divide(10, 4) = {quotient}");
|
Log($"Divide(10, 4) = {quotient}");
|
||||||
|
|
||||||
string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
|
var echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
|
||||||
Log(echo);
|
Log(echo);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Server-side exceptions are forwarded to the client
|
// Server-side exceptions are forwarded to the client
|
||||||
async Task ServerExceptionsExampleAsync()
|
async Task ServerExceptionsExampleAsync(PipeClient<IPipeServerMethods> client)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -109,13 +102,13 @@ async Task ServerExceptionsExampleAsync()
|
|||||||
// InvokeAsync with a CancellationToken: the client stops waiting when the token is canceled.
|
// InvokeAsync with a CancellationToken: the client stops waiting when the token is canceled.
|
||||||
// PipeMethodCalls does not propagate cancellation to the server, so an explicit
|
// PipeMethodCalls does not propagate cancellation to the server, so an explicit
|
||||||
// CancelOperation call with the operation id stops the server-side work as well.
|
// CancelOperation call with the operation id stops the server-side work as well.
|
||||||
async Task CancellationExampleAsync()
|
async Task CancellationExampleAsync(PipeClient<IPipeServerMethods> client)
|
||||||
{
|
{
|
||||||
using var invokeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
using var invokeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||||
var operationId = Guid.NewGuid();
|
var operationId = Guid.NewGuid();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
int result = await client.InvokeAsync(c => c.SlowOperationAsync(2000, operationId), invokeCts.Token);
|
var result = await client.InvokeAsync(c => c.SlowOperationAsync(2000, operationId), invokeCts.Token);
|
||||||
Log($"SlowOperationAsync = {result}");
|
Log($"SlowOperationAsync = {result}");
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
@@ -126,64 +119,20 @@ async Task CancellationExampleAsync()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Kill the server process if it does not respond in time, then restart it
|
// Kill the server process if it does not respond in time, then restart it
|
||||||
async Task KillOnTimeoutExampleAsync()
|
async Task KillOnTimeoutExampleAsync(ServerConnection connection)
|
||||||
{
|
{
|
||||||
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await client.InvokeAsync(c => c.SlowOperationAsync(30_000, Guid.NewGuid()), timeoutCts.Token);
|
await connection.Client.InvokeAsync(c => c.SlowOperationAsync(30_000, Guid.NewGuid()), timeoutCts.Token);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (serverProcess is not null)
|
catch (OperationCanceledException)
|
||||||
{
|
{
|
||||||
Log("Server did not respond within 1 s. Killing server process...");
|
Log("Server did not respond within 1 s. Killing server process...");
|
||||||
serverProcess.Kill(entireProcessTree: true);
|
await connection.KillAndRestartAsync();
|
||||||
await serverProcess.WaitForExitAsync();
|
|
||||||
serverProcess.Dispose();
|
|
||||||
client.Dispose();
|
|
||||||
|
|
||||||
Log("Restarting server...");
|
|
||||||
await StartServerAndConnectAsync(pipeName);
|
|
||||||
Log("Reconnected to server.");
|
Log("Reconnected to server.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Simulate a server crash
|
// Simulate a server crash
|
||||||
async Task CrashExampleAsync() => await client.InvokeAsync(c => c.Crash(42));
|
async Task CrashExampleAsync(PipeClient<IPipeServerMethods> client) => 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)
|
|
||||||
Log($"Server process exited abnormally (exit code {process.ExitCode}).");
|
|
||||||
};
|
|
||||||
serverProcess = process;
|
|
||||||
|
|
||||||
client = new PipeClient<IServerMethods>(new JsonFieldsPipeSerializer(), pipeName);
|
|
||||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
||||||
await client.ConnectAsync(cts.Token);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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");
|
|
||||||
ProcessStartInfo startInfo;
|
|
||||||
if (File.Exists(serverExe))
|
|
||||||
{
|
|
||||||
startInfo = new ProcessStartInfo(serverExe);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
startInfo = new ProcessStartInfo("dotnet");
|
|
||||||
startInfo.ArgumentList.Add(Path.Combine(baseDir, "PipeServer.dll"));
|
|
||||||
}
|
|
||||||
startInfo.ArgumentList.Add($"{PipeConstants.PipeNameArgPrefix}{pipeName}");
|
|
||||||
startInfo.UseShellExecute = false;
|
|
||||||
|
|
||||||
return Process.Start(startInfo)
|
|
||||||
?? throw new InvalidOperationException("Server konnte nicht gestartet werden.");
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
using PipeMethodCalls;
|
||||||
|
using PipeShared;
|
||||||
|
using System.Diagnostics;
|
||||||
|
|
||||||
|
namespace PipeClient;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Manages a pipe client and any server process it starts.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class ServerConnection(string pipeName, Action<string> log) : IDisposable
|
||||||
|
{
|
||||||
|
private Process? _process;
|
||||||
|
private PipeClient<IPipeServerMethods>? _client;
|
||||||
|
|
||||||
|
private string PipeName { get; } = pipeName;
|
||||||
|
|
||||||
|
public PipeClient<IPipeServerMethods> Client =>
|
||||||
|
_client ?? throw new InvalidOperationException("Not connected to server.");
|
||||||
|
|
||||||
|
public async Task StartAsync()
|
||||||
|
{
|
||||||
|
if (_client?.State == PipeState.Connected)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var process = StartServerProcess(PipeName);
|
||||||
|
process.EnableRaisingEvents = true;
|
||||||
|
process.Exited += (_, _) =>
|
||||||
|
{
|
||||||
|
if (process.ExitCode != 0)
|
||||||
|
log($"Server process exited abnormally (exit code {process.ExitCode}).");
|
||||||
|
};
|
||||||
|
_process = process;
|
||||||
|
|
||||||
|
_client = new PipeClient<IPipeServerMethods>(new JsonFieldsPipeSerializer(), PipeName);
|
||||||
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||||
|
await _client.ConnectAsync(cts.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Kills the owned server process, if any, and starts a new one.
|
||||||
|
/// </summary>
|
||||||
|
public async Task KillAndRestartAsync()
|
||||||
|
{
|
||||||
|
if (_process is not null)
|
||||||
|
{
|
||||||
|
_process.Kill(entireProcessTree: true);
|
||||||
|
await _process.WaitForExitAsync();
|
||||||
|
_process.Dispose();
|
||||||
|
_process = null;
|
||||||
|
}
|
||||||
|
_client?.Dispose();
|
||||||
|
_client = null;
|
||||||
|
|
||||||
|
await StartAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Waits up to <paramref name="milliseconds"/> for the server process to exit.
|
||||||
|
/// </summary>
|
||||||
|
public bool WaitForServerExit(int milliseconds, out int exitCode)
|
||||||
|
{
|
||||||
|
exitCode = 0;
|
||||||
|
if (_process is null || !_process.WaitForExit(milliseconds))
|
||||||
|
return false;
|
||||||
|
exitCode = _process.ExitCode;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
// Disposing the client closes the pipe, the server then exits.
|
||||||
|
_client?.Dispose();
|
||||||
|
_client = null;
|
||||||
|
if (_process is null)
|
||||||
|
return;
|
||||||
|
if (!_process.WaitForExit(5000))
|
||||||
|
_process.Kill();
|
||||||
|
_process.Dispose();
|
||||||
|
_process = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start server process (Server is referenced, so its output is copied next to the client).
|
||||||
|
private static Process StartServerProcess(string pipeName)
|
||||||
|
{
|
||||||
|
var baseDir = AppContext.BaseDirectory;
|
||||||
|
var serverExe = Path.Combine(baseDir, OperatingSystem.IsWindows() ? "PipeServer.exe" : "PipeServer");
|
||||||
|
ProcessStartInfo startInfo;
|
||||||
|
if (File.Exists(serverExe))
|
||||||
|
{
|
||||||
|
startInfo = new ProcessStartInfo(serverExe);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
startInfo = new ProcessStartInfo("dotnet");
|
||||||
|
startInfo.ArgumentList.Add(Path.Combine(baseDir, "PipeServer.dll"));
|
||||||
|
}
|
||||||
|
startInfo.ArgumentList.Add($"{PipeConstants.PipeNameArgPrefix}{pipeName}");
|
||||||
|
startInfo.UseShellExecute = false;
|
||||||
|
|
||||||
|
return Process.Start(startInfo)
|
||||||
|
?? throw new InvalidOperationException("Server could not be started.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
using PipeShared;
|
using PipeShared;
|
||||||
using PipeMethodCalls;
|
using PipeMethodCalls;
|
||||||
using Server;
|
using PipeServer;
|
||||||
|
|
||||||
string pipeName = args.FirstOrDefault(static a => a.StartsWith(PipeConstants.PipeNameArgPrefix, StringComparison.Ordinal))?
|
var pipeName = args.FirstOrDefault(static a => a.StartsWith(PipeConstants.PipeNameArgPrefix, StringComparison.Ordinal))?
|
||||||
[PipeConstants.PipeNameArgPrefix.Length..] ?? "PipeDemo";
|
[PipeConstants.PipeNameArgPrefix.Length..] ?? "PipeDemo";
|
||||||
|
|
||||||
Console.WriteLine($"Server started. Pipe: {pipeName}");
|
Console.WriteLine($"Server started. Pipe: {pipeName}");
|
||||||
|
|
||||||
// Exceptions in handler methods are caught by PipeMethodCalls and sent to the client
|
// Exceptions in handler methods are caught by PipeMethodCalls and sent to the client
|
||||||
// (client receives PipeInvokeFailedException with the server exception details).
|
// (client receives PipeInvokeFailedException with the server exception details).
|
||||||
var server = new PipeServer<IServerMethods>(
|
var server = new PipeServer<IPipeServerMethods>(
|
||||||
new JsonFieldsPipeSerializer(),
|
new JsonFieldsPipeSerializer(),
|
||||||
pipeName,
|
pipeName,
|
||||||
() => new ServerMethods());
|
() => new ServerMethods());
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
using PipeShared;
|
using System.Collections.Concurrent;
|
||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
|
using PipeShared;
|
||||||
|
|
||||||
namespace Server;
|
namespace PipeServer;
|
||||||
|
|
||||||
public class ServerMethods : IServerMethods
|
public class ServerMethods : IPipeServerMethods
|
||||||
{
|
{
|
||||||
public int Add(int a, int b) => a + b;
|
public int Add(int a, int b) => a + b;
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ public class ServerMethods : IServerMethods
|
|||||||
public double Divide(double a, double b)
|
public double Divide(double a, double b)
|
||||||
{
|
{
|
||||||
if (b == 0)
|
if (b == 0)
|
||||||
throw new DivideByZeroException("Division durch 0 ist nicht erlaubt.");
|
throw new DivideByZeroException("Division by 0 not allowed.");
|
||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ public class ServerMethods : IServerMethods
|
|||||||
{
|
{
|
||||||
await Task.Delay(50);
|
await Task.Delay(50);
|
||||||
if (string.IsNullOrEmpty(text))
|
if (string.IsNullOrEmpty(text))
|
||||||
throw new ArgumentException("Text darf nicht leer sein.", nameof(text));
|
throw new ArgumentException("Text must not be empty.", nameof(text));
|
||||||
return $"Echo: {text}";
|
return $"Echo: {text}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ using System.Numerics;
|
|||||||
|
|
||||||
namespace PipeShared;
|
namespace PipeShared;
|
||||||
|
|
||||||
public interface IServerMethods
|
public interface IPipeServerMethods
|
||||||
{
|
{
|
||||||
int Add(int a, int b);
|
int Add(int a, int b);
|
||||||
Vector3 AddVector(Vector3 a, Vector3 b);
|
Vector3 AddVector(Vector3 a, Vector3 b);
|
||||||
Reference in New Issue
Block a user