c# 利用管道通信
简介
NamedPipeServerStream Class (System.IO.Pipes) | Microsoft Docs
如何:将命名管道用于网络进程间通信|微软文档 (microsoft.com)
[C#]基于命名管道的一对多进程间通讯 - 写代码的相声演员 - 博客园 (cnblogs.com)
一、官方的一个列子
/// <summary> /// 服务端---当前例子写入数据 /// </summary> static void TestServer() { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out)) { // Wait for a client to connect pipeServer.WaitForConnection(); try { // Read user input and send that to the client process. using (StreamWriter sw = new StreamWriter(pipeServer)) { for (int i = 0; i < 20; i++) { sw.AutoFlush = true; sw.WriteLine($"Enter text: {i}"); pipeServer.WaitForPipeDrain(); } } } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } }
/// <summary> /// 客户端--当前例子接收数据 /// </summary> static void TestCilent() { Thread thread = new Thread(() => { using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.In)) { // Connect to the pipe or wait until the pipe is available. pipeClient.Connect(); Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances); using (StreamReader sr = new StreamReader(pipeClient)) { // Display the read text to the console string temp; while ((temp = sr.ReadLine()) != null) { Console.WriteLine("Received from server: {0}", temp); Thread.Sleep(200); } } } }); //thread.IsBackground = true; //thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
调用示例
for (int i = 0; i < 5; i++) { TestCilent(); TestServer(); }