在 C# 开发中,管道通信是一种高效、安全的进程间通信(IPC)方式。尤其适用于同一台机器上的不同进程之间交换数据。本文将手把手教你如何使用 NamedPipeServerStream 和 NamedPipeClientStream 实现读写器协作,即使你是编程小白也能轻松上手!
命名管道(Named Pipe)是 Windows 系统提供的一种 IPC 机制。它允许两个或多个进程通过一个“管道”进行双向或单向的数据传输。在 .NET 中,我们通过 System.IO.Pipes 命名空间下的类来操作命名管道。
我们将创建两个控制台应用程序:一个作为服务器(写入器),另一个作为客户端(读取器)。
using System;using System.IO;using System.IO.Pipes;using System.Text;class PipeServer{ static void Main() { Console.WriteLine("[服务器] 启动中..."); // 创建命名管道服务器流 using (var server = new NamedPipeServerStream("MyPipe", PipeDirection.Out)) { Console.WriteLine("[服务器] 等待客户端连接..."); server.WaitForConnection(); // 阻塞直到客户端连接 Console.WriteLine("[服务器] 客户端已连接!"); // 向管道写入数据 string message = "Hello from C# 管道服务器!"; byte[] buffer = Encoding.UTF8.GetBytes(message); server.Write(buffer, 0, buffer.Length); Console.WriteLine($"[服务器] 已发送消息: {message}"); } Console.WriteLine("[服务器] 关闭。"); Console.ReadKey(); }} using System;using System.IO;using System.IO.Pipes;using System.Text;class PipeClient{ static void Main() { Console.WriteLine("[客户端] 尝试连接服务器..."); // 创建命名管道客户端流 using (var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.In)) { try { client.Connect(5000); // 最多等待5秒 Console.WriteLine("[客户端] 成功连接到服务器!"); // 从管道读取数据 byte[] buffer = new byte[1024]; int bytesRead = client.Read(buffer, 0, buffer.Length); string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine($"[客户端] 收到消息: {message}"); } catch (TimeoutException) { Console.WriteLine("[客户端] 连接超时,请确保服务器正在运行。"); } } Console.WriteLine("[客户端] 关闭。"); Console.ReadKey(); }} - 管道名称(如 "MyPipe")必须在服务端和客户端保持一致。
- 使用 using 语句确保资源正确释放。
- PipeDirection.Out 表示只写,PipeDirection.In 表示只读,也可以使用 PipeDirection.InOut 实现双向通信。
- 这种 C# 进程间通信 方式比文件或网络套接字更轻量、更安全。
本文深入讲解了 C# 管道通信、NamedPipeServerStream、NamedPipeClientStream 以及 C# 进程间通信 的实际应用,帮助开发者快速掌握这一重要技术。
现在你已经掌握了 C# 中命名管道的基本用法!快去尝试构建自己的 IPC 应用吧~
本文由主机测评网于2025-12-15发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025128155.html