public void ClientServerConnectionTest() { Helper.RunMta(() => { var pipeName = Guid.NewGuid().ToString("N"); var server = new NamedPipeServerStreams(pipeName); var client = new NamedPipeClientStreams(pipeName); var serverWaitHandle = new ManualResetEventSlim(); var clientWaitHandle = new ManualResetEventSlim(); Task.Run(() => { try { server.WaitForConnection(); Console.WriteLine("Server connected"); serverWaitHandle.Set(); } catch (Exception ex) { Console.WriteLine(ex); } }); Task.Run(() => { try { client.Connect(); Console.WriteLine("Client connected"); clientWaitHandle.Set(); } catch (Exception ex) { Console.WriteLine(ex); } }); var success = WaitHandle.WaitAll(new[] { serverWaitHandle.WaitHandle, clientWaitHandle.WaitHandle }, 500); client.Dispose(); server.Dispose(); Assert.AreEqual(true, success); }); }
private static void MessageLoop() { // TODO use NamedPipeServer EventHandler <ConsoleExitEventArgs> consoleExitHandler = null; NamedPipeServerStreams pipeServer = null; var exit = false; var lastTransmission = DateTime.MinValue; Timer timer = null; try { var pipeName = "KsWare.PrivilegedExecutor" + (SingleInstance ? "" : Process.GetCurrentProcess().Id.ToString()); pipeServer = new NamedPipeServerStreams(pipeName); Console.WriteLine($"Named pipe created '{pipeName}*'"); var reader = pipeServer.Reader; var writer = pipeServer.Writer; consoleExitHandler = (sender, e) => { Console.WriteLine($"[SERVER] Close because {e.ExitReason}. Shutting down..."); exit = true; pipeServer?.Close(); }; Console.Exit += consoleExitHandler; lastTransmission = DateTime.Now; timer = new Timer(state => { Console.WriteLine("Close because idle since 5 minutes. Shutting down..."); exit = true; pipeServer?.Close(); }, null, TimeSpan.FromMinutes(5), TimeSpan.FromMilliseconds(-1)); while (!exit) { try { Console.WriteLine("WaitForConnection..."); pipeServer.WaitForConnection(); var command = reader.ReadLine(); if (command == null) { continue; } Console.WriteLine($"Command received: {command}"); lastTransmission = DateTime.Now; timer.Change(TimeSpan.FromMinutes(5), TimeSpan.FromMilliseconds(-1)); if (command == "-close") { Console.WriteLine("Server close requested by client. Shutting down..."); break; } var args = SplitCommandLine(command); var exitCode = ExecuteGeneric(args); writer.WriteLine(exitCode); writer.Flush(); } catch (IOException ex) { // Catch the IOException that is raised if the pipe is broken or disconnected. Console.WriteLine($"ERROR: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"ERROR: {ex.Message}"); } finally { pipeServer.WaitForPipeDrain(); if (pipeServer.IsConnected) { pipeServer.Disconnect(); } } } } catch (Exception ex) { Console.WriteLine($@"ERROR: {ex.Message}"); } finally { timer?.Dispose(); if (consoleExitHandler != null) { Console.Exit -= consoleExitHandler; } pipeServer?.Dispose(); } }