进程之间的通信-命名管道通信

管道通信包括匿名管道和命名管道,匿名管道只能用在父子进程之间,命名管道可以用在两个进程甚至跨服务器通信。

服务器端代码:

  private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (NamedPipeClientStream pipeClient =
              new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None))
                {
                    pipeClient.Connect();
                    using (StreamWriter sw = new StreamWriter(pipeClient))
                    {
                        sw.WriteLine(textBox1.Text);
                        sw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

服务器端代码:

  private async  void Form1_Load(object sender, EventArgs e)
        {
          await   Task.Run(() => 
            {

                while (true)
                {
                    using (NamedPipeServerStream pipeServer =
             new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1))
                    {
                        try
                        {
                            pipeServer.WaitForConnection();
                            pipeServer.ReadMode = PipeTransmissionMode.Byte;
                            using (StreamReader sr = new StreamReader(pipeServer))
                            {
                                string con = sr.ReadToEnd();

                                this.listBox1.Invoke(new Action(() =>
                                {
                                    listBox1.Items.Add(con);

                                }));


                            }
                        }
                        catch (IOException o)
                        {
                            throw o;
                        }
                    }
                }
            });
        }

猜你喜欢

转载自www.cnblogs.com/dangnianxiaoqingxin/p/12806515.html