NamedPipeServerStream
是 .NET Framework 和 .NET Core 中提供的一个类,用于创建和操作命名管道的服务器端。命名管道是一种在同一台计算机上或不同计算机之间进行进程间通信的机制。
命名管道允许两个或多个进程通过共享的管道进行通信。其中一个进程充当服务器,创建管道并等待客户端连接。其他进程充当客户端,连接到服务器创建的管道,并通过管道进行数据交换。
NamedPipeServerStream
类提供了创建命名管道服务器端的功能。它允许你指定管道的名称、方向(输入、输出或双向)和一些其他选项。一旦服务器端创建并等待连接,客户端可以使用 NamedPipeClientStream
类连接到该管道,并进行数据交换。
本次只演示客户端-服务端通讯:
服务端:
/// <summary>/// 服务端/// </summary>public partial class FrmTest : Form{private NamedPipeServerStream pipeServer;volatile bool _receive = true;public FrmTest(){InitializeComponent();// 连接到命名管道pipeServer = new NamedPipeServerStream("Test", PipeDirection.In);Thread thread = new Thread(() =>{while (_receive){try{if(!pipeServer.IsConnected){Console.WriteLine("等待客户端连接。。。");pipeServer.WaitForConnection();Console.WriteLine("客户端已连接。。。");}// 读取字节大小byte[] sizeBuffer = new byte[sizeof(int)];pipeServer.Read(sizeBuffer, 0, sizeBuffer.Length);int messageSize = BitConverter.ToInt32(sizeBuffer, 0);// 消息内容byte[] responseBytes = new byte[messageSize];Console.WriteLine("等待客户端发送消息。。。");int bytesRead = pipeServer.Read(responseBytes, 0, responseBytes.Length);Console.WriteLine("客户端已发送消息。。。");string response = Encoding.UTF8.GetString(responseBytes, 0, bytesRead);this.ExecBeginInvoke(() =>{this.richTextBox1.AppendText(DateTime.Now.ToStringFromDateTime() + ":\r\n" + response + "\r\n");});pipeServer.Disconnect();}catch (Exception ex){Trace.WriteLine(ex.Message+"\r\n"+ex.StackTrace);}finally{}}});thread.Start();}private void button1_Click(object sender, System.EventArgs e){}private void FrmTest_FormClosing(object sender, FormClosingEventArgs e){_receive = false;if (pipeServer.IsConnected){pipeServer.Disconnect();}// 关闭管道pipeServer.Close();this.Dispose();Application.ExitThread();Application.Exit();Process.GetCurrentProcess().Kill();}private void FrmTest_FormClosed(object sender, FormClosedEventArgs e){}}
客户端:
/// <summary>/// 客户端/// </summary>public partial class FrmTest : Form{public FrmTest(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){string msg = this.richTextBox1.Text;// 连接到命名管道服务器using (NamedPipeClientStream clientStream = new NamedPipeClientStream(".", "Test", PipeDirection.Out)){try{Console.WriteLine("等待连接到服务器");clientStream.Connect(5000);Console.WriteLine("已连接到服务器");// 向服务器发送消息string message = msg;byte[] messageBytes = Encoding.UTF8.GetBytes(message);byte[] msgSize = Encoding.UTF8.GetBytes(messageBytes.Length.ToString());clientStream.Write(msgSize, 0, msgSize.Length);clientStream.Write(messageBytes, 0, messageBytes.Length);Console.WriteLine("已发送消息至服务器");}catch(Exception ex){Console.WriteLine("连接超时。。。");}finally{clientStream.Close();}}}private void FrmTest_FormClosing(object sender, FormClosingEventArgs e){this.Dispose();Application.ExitThread();Application.Exit();}}