C#进程间通信-匿名管道通信

这里是官方文档,已经很完善了,Server拉Client,Server发Client收。
我根据自己的需要进行了一些修改:

  1. 要由被拉起的子进程来发送,父进程接收;
  2. 支持持续发送和接收消息;
  3. 对上述操作进行类的封装。
    代码如下:
Client端代码
using System.IO.Pipes;

namespace TestPipe
{
    class AnonymousPipeClient
    {
        private PipeStream pipeClient;
        private StreamWriter sw;
        public AnonymousPipeClient(PipeDirection direction, string pipeHandleAsString)
        {
            try
            {
                pipeClient = new AnonymousPipeClientStream(direction, pipeHandleAsString);
                sw = new StreamWriter(pipeClient);
                sw.AutoFlush = true;
                Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.", pipeClient.TransmissionMode);
            }
            catch (Exception e)
            {
                Console.WriteLine("[CLIENT] Construct error: {0}", e.Message);
            }
        }

        public void Send()
        {
            try
            {
                // Send a 'sync message' and wait for client to receive it.
                sw.WriteLine("SYNC");
                sw.Flush();
                pipeClient.WaitForPipeDrain();
                // Send the console input to the client process.
                Console.Write("[CLIENT] Enter text: ");
                sw.WriteLine(Console.ReadLine());
            }
            catch (IOException e)
            {
                Console.WriteLine("[CLIENT] Send error: {0}", e.Message);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            AnonymousPipeClient client = new AnonymousPipeClient(PipeDirection.Out, args[0]);
            while (true)
            {
                client.Send();
            }
            
            Console.Write("[CLIENT] Press Enter to continue...");
            Console.ReadLine();
        }
    }
}
Server端代码
using System.Diagnostics;
using System.IO.Pipes;

namespace TestPipe
{
    class AnonymousPipeServer
    {
        public AnonymousPipeServerStream PipeServer { get; private set; }
        private StreamReader sr;
        public AnonymousPipeServer(PipeDirection direction)
        {
            try
            {
                PipeServer = new AnonymousPipeServerStream(direction, HandleInheritability.Inheritable);
                sr = new StreamReader(PipeServer);
                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", PipeServer.TransmissionMode);
            }
            catch (Exception e)
            {
                Console.WriteLine("[SERVER] Construct error: {0}", e.Message);
            }
        }

        public void Receive()
        {
            while (true)
            {
                string temp;
                bool printed = false;
                // Wait for 'sync message' from the server.
                do
                {
                    temp = sr.ReadLine();
                    if (temp == null || temp.Equals(""))
                    {
                        if (!printed)
                        {
                            Console.WriteLine("[SERVER] Wait for sync...");
                            printed = true;
                        }
                    }
                    temp = temp != null ? temp : "";
                    Thread.Sleep(100);
                }
                while (!temp.StartsWith("SYNC"));
                printed = false;

                // Read the server data and echo to the console.
                temp = sr.ReadLine();
                if (temp != null)
                {
                    Console.WriteLine("[SERVER] Echo: " + temp);
                }
                Thread.Sleep(50);
            }
        }
    }
    class Program
    {
        static void Main()
        {
            AnonymousPipeServer anonymousPipeServer = new AnonymousPipeServer(PipeDirection.In);

            Process pipeClient = new Process();
            pipeClient.StartInfo.FileName = "../../../../AnonymousPipeClient/bin/Debug/net6.0/AnonymousPipeClient.exe";
            // Pass the client process a handle to the server.
            pipeClient.StartInfo.Arguments = anonymousPipeServer.PipeServer.GetClientHandleAsString();
            pipeClient.StartInfo.UseShellExecute = false;
            pipeClient.Start();

            anonymousPipeServer.PipeServer.DisposeLocalCopyOfClientHandle();
            anonymousPipeServer.Receive();

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皓月如我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值