欢迎来到陆季疵的博客

人生莫作远行客,远行莫戍黄沙碛。黄沙碛下八月时, 霜风裂肤百草衰。尘沙晴天迷道路,河水悠悠向东去。 胡笳听彻双泪流,羁魂惨惨生边愁。原头猎火夜相向, 马蹄蹴蹋层冰上。不似京华侠少年,清歌妙舞落花前。

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();
            }

 

posted @ 2021-11-03 12:36  陆季疵  阅读(568)  评论(0编辑  收藏  举报
//《!--看板娘--> //https://www.cnblogs.com/ZTianming/p/14618913.html