A Simple Console Application Demonstrating Named Pipe IPC
Named pipes offer a robust method for inter-process communication (IPC) on a single machine. This example illustrates a basic IPC connection using named pipes.
Program 1 acts as the message sender, while Program 2 receives the message. Program 1 sends "Hello World," and Program 2 replies with "Roger That."
Server (Program 2):
<code class="language-csharp">using System; using System.IO.Pipes; namespace ServerApp { class Program { static void Main(string[] args) { string pipeName = "MyPipe"; // Named pipe identifier using (var server = new NamedPipeServerStream(pipeName)) { server.WaitForConnection(); Console.WriteLine("Client connected."); using (var reader = new StreamReader(server)) using (var writer = new StreamWriter(server)) { string message = reader.ReadLine(); Console.WriteLine($"Received: {message}"); writer.WriteLine("Roger That"); writer.Flush(); } } } } }</code>
Client (Program 1):
<code class="language-csharp">using System; using System.IO.Pipes; namespace ClientApp { class Program { static void Main(string[] args) { string pipeName = "MyPipe"; // Must match server's pipe name using (var client = new NamedPipeClientStream(pipeName)) { client.Connect(); Console.WriteLine("Connected to server."); using (var reader = new StreamReader(client)) using (var writer = new StreamWriter(client)) { writer.WriteLine("Hello World"); writer.Flush(); Console.WriteLine("Sent: Hello World"); string response = reader.ReadLine(); Console.WriteLine($"Received: {response}"); } } } } }</code>
To run: Start the ServerApp.exe
first, then run ClientApp.exe
. This demonstrates the fundamental principles of using named pipes for simple inter-process communication. Remember to adjust the pipeName
if necessary.
The above is the detailed content of How Can Named Pipes Facilitate Inter-Process Communication in a Simple Console Application?. For more information, please follow other related articles on the PHP Chinese website!