using System.IO.Pipes; NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1); pipeServer.BeginWaitForConnection((IAsyncResult result) => { // wait for the client to connect pipeServer.EndWaitForConnection(result); // read data from the client StreamReader reader = new StreamReader(pipeServer); string data = reader.ReadLine(); // send response to the client StreamWriter writer = new StreamWriter(pipeServer); writer.WriteLine("Response from server: " + data); writer.Flush(); // disconnect from the client pipeServer.Disconnect(); }, null);
using System.IO.Pipes; void WaitForConnection() { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1); IAsyncResult asyncResult = pipeServer.BeginWaitForConnection(null, null); asyncResult.AsyncWaitHandle.WaitOne(); pipeServer.EndWaitForConnection(asyncResult); // read data from the client StreamReader reader = new StreamReader(pipeServer); string data = reader.ReadLine(); // send response to the client StreamWriter writer = new StreamWriter(pipeServer); writer.WriteLine("Response from server: " + data); writer.Flush(); // disconnect from the client pipeServer.Disconnect(); WaitForConnection(); }This example creates a named pipe server with the name "testpipe", starts an asynchronous operation to wait for a client to connect using the BeginWaitForConnection method, and waits for the connection to complete using the AsyncWaitHandle.WaitOne method. After the client connects, it reads data, sends a response, and disconnects from the client. Then it starts waiting for another client connection using the recursive method call WaitForConnection.