NamedPipeStream的使用具体案例如下:
using System; using System.Data; using System.Data.SQLite; using System.IO; using System.IO.Pipes; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SupremeConsole { class Program { static void Main(string[] args) { #region 测试 NamedPipeStream new Thread(new ThreadStart(PipeServerMessage)).Start(); new Thread(new ThreadStart(PipeClientMessage)).Start(); #endregion }
public static void PipeServerMessage() { var s = new NamedPipeServerStream("pipedream", PipeDirection.InOut, 1, PipeTransmissionMode.Message); s.WaitForConnection(); while (true) { byte[] msg = Encoding.UTF8.GetBytes("Hello"); s.Write(msg, 0, msg.Length); Console.WriteLine($"PipeServer 服务端 数据:{Encoding.UTF8.GetString(ReadMessage(s))}"); } } public static void PipeClientMessage() { var s = new NamedPipeClientStream("pipedream"); s.Connect(); s.ReadMode = PipeTransmissionMode.Message; while (true) { Console.WriteLine($"PipeClient 收到数据:{Encoding.UTF8.GetString(ReadMessage(s))}"); Thread.Sleep(TimeSpan.FromSeconds(2)); byte[] msg = Encoding.UTF8.GetBytes("Hello right back!"); s.Write(msg, 0, msg.Length); Console.WriteLine($"PipeClient 发送数据:Hello right back!"); //Thread.Sleep(TimeSpan.FromSeconds(2)); //s.WriteByte(200); // Send the value 200 back. } } static byte[] ReadMessage(PipeStream s) { MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[0x1000]; // Read in 4 KB blocks do { ms.Write(buffer, 0, s.Read(buffer, 0, buffer.Length)); } while (!s.IsMessageComplete); return ms.ToArray(); } } }
测试结果: