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

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

服务器端代码:

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

 

posted @ 2020-04-30 07:14  当年小清新  阅读(283)  评论(0编辑  收藏  举报