Pipe管道--NamedPipe与AnonymousPipe

管道分为命名管道和匿名管道

1.    命名管道简介

"命名管道"或"命名管线"(Named Pipes)是一种简单的进程间通信(I P C)机制,Microsoft Windows NT,Windows 2000,Windows 95以及Windows 98均提供了对它的支持(但不包括Windows CE).命名管道可在同一台计算机的不同进程之间,或在跨越一个网络的不同计算机的不同进程之间,支持可靠的,单向或双向的数据通信.用命名管道来设计应用程序实际非常简单,并不需要事先深入掌握基层网络传送协议(如T C P / I P或I P X)的知识.这是由于命名管道利用了微软网络提供者(M S N P)重定向器,通过一个网络,在各进程间建立通信.这样一来,应用程序便不必关心网络协议的细节.之所以要用命名管道作为自己的网络通信方案,一项重要的原因是它们充分利用了Windows NT及Windows 2000内建的安全特性.

2.命名管道作用

这里有一个可采纳命令管道的例子.假定我们要开发一个数据管理系统,只允许一个指定的用户组进行操作.想像在自己的办公室中,有一部计算机,其中保存着公司的秘密.我们要求只有公司的管理人员,才能访问及处理这些秘密.假定在自己的工作站机器上,公司内的每名员工都可看到网络上的这台计算机.然而,我们并不希望普通员工取得对机密材料的访问权.在这种情况下,命名管道可发挥出很好的作用,因为我们可开发一个服务器应用程序,令其以来自客户机的请求为准,对公司的秘密进行安全操作.服务器可将客户访问限制在管理人员身上,用Windows NT或新版Windows 2000自带的安全机制,便可非常轻松地做到这一点.在此要记住的一个重点是,将命名管道作为一种网络编程方案使用时,它实际上建立一个简单的客户机/服务器数据通信体系,可在其中可靠地传输数据.

3. 命名管道优点

使用比较方便,并且不需要声明端口号之类的,在程序中不需要关心权限之类的。

4. 命名管道限制(我个人认为)

管道只能一对一链接通信。

5. 命名管道通讯的实现以及匿名管道的实现如下:

        #region Anonymouspipe

        static string txID = null;
        static string rxID = null;
        public static void AnonymousPipeServer()
        {
            string clientExe = @"F:PersonLongtengLongtengSlnConsoleAppTestAnonymousPipeinDebugConsoleAppTestAnonymousPipe.exe";
            HandleInheritability inherit = HandleInheritability.Inheritable;
            using (var tx = new AnonymousPipeServerStream(PipeDirection.Out, inherit))
            using (var rx = new AnonymousPipeServerStream(PipeDirection.In, inherit))
            {
                txID = tx.GetClientHandleAsString();
                rxID = rx.GetClientHandleAsString();
                var startInfo = new ProcessStartInfo(clientExe, txID + " " + rxID);
                startInfo.UseShellExecute = false; // Required for child process
                Process p = Process.Start(startInfo);
                tx.DisposeLocalCopyOfClientHandle(); // Release unmanaged
                rx.DisposeLocalCopyOfClientHandle(); // handle resources.
                //tx.WriteByte(100);
                //Console.WriteLine("Server received: " + rx.ReadByte());
                //p.WaitForExit();    
                while (true)
                {
                    tx.WriteByte(100);
                    Console.WriteLine("Server received: " + rx.ReadByte());
                }

            }
        }

        //ClientDemo.exe的内容
        public static void AnonymousPipeClient()
        {
            //Thread.Sleep(TimeSpan.FromSeconds(1));
            //string rxID = args[0]; // Note we're reversing the
            //string txID = args[1]; // receive and transmit roles.
            using (var rx = new AnonymousPipeClientStream(PipeDirection.In, rxID))
            using (var tx = new AnonymousPipeClientStream(PipeDirection.Out, txID))
            {
                //Console.WriteLine("Client received: " + rx.ReadByte());
                //tx.WriteByte(200);
                while (true)
                {
                    Console.WriteLine("Client received: " + rx.ReadByte());
                    tx.WriteByte(200);
                }
            }
        }

        //public static void AnonymousPipeServer1()
        //{
        //    string clientExe = @"d:PipeDemoClientDemo.exe";
        //    HandleInheritability inherit = HandleInheritability.Inheritable;
        //    using (var tx = new AnonymousPipeServerStream(PipeDirection.Out, inherit))
        //    using (var rx = new AnonymousPipeServerStream(PipeDirection.In, inherit))
        //    {
        //        string txID = tx.GetClientHandleAsString();
        //        string rxID = rx.GetClientHandleAsString();
        //        var startInfo = new ProcessStartInfo(clientExe, txID + " " + rxID);
        //        startInfo.UseShellExecute = false; // Required for child process
        //        Process p = Process.Start(startInfo);
        //        tx.DisposeLocalCopyOfClientHandle(); // Release unmanaged
        //        rx.DisposeLocalCopyOfClientHandle(); // handle resources.
        //        tx.WriteByte(100);
        //        Console.WriteLine("Server received: " + rx.ReadByte());
        //        p.WaitForExit();
        //    }
        //}

        ////ClientDemo.exe的内容
        //public static void AnonymousPipeClient1()
        //{
        //    string rxID = args[0]; // Note we're reversing the
        //    string txID = args[1]; // receive and transmit roles.
        //    using (var rx = new AnonymousPipeClientStream(PipeDirection.In, rxID))
        //    using (var tx = new AnonymousPipeClientStream(PipeDirection.Out, txID))
        //    {
        //        Console.WriteLine("Client received: " + rx.ReadByte());
        //        tx.WriteByte(200);
        //    }
        //}

        #endregion

        #region Namepipe

        public static void PipeServer()
        {
            var s = new System.IO.Pipes.NamedPipeServerStream("pipedream");
            s.WaitForConnection();
            while (true)
            {
                s.WriteByte(100);
                Console.WriteLine($"PipeServer 收到 客户端 数据:{s.ReadByte()}");
            }
        }

        public static void PipeClient()
        {
            var s = new System.IO.Pipes.NamedPipeClientStream("pipedream");
            s.Connect();
            while (true)
            {
                Console.WriteLine($"PipeClient 收到服务端数据:{s.ReadByte()}");
                Thread.Sleep(TimeSpan.FromSeconds(2));
                s.WriteByte(200); // Send the value 200 back.
            }
        }


        public static void PipeServerMessage()
        {
            var s = new System.IO.Pipes.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");
            var s = new NamedPipeClientStream("192.168.1.199", "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!1111");
                s.Write(msg, 0, msg.Length);
                Console.WriteLine($"PipeClient 发送数据:Hello right back!111");
                //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();
        }

        #endregion

 参考链接:https://www.cnblogs.com/shanranlei/p/3629901.html

龙腾一族至尊龙骑
原文地址:https://www.cnblogs.com/1175429393wljblog/p/15166953.html