C# 两个进程之间通讯(管道通信 )

Posted 高软玩家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 两个进程之间通讯(管道通信 )相关的知识,希望对你有一定的参考价值。

  #region  客户端
        NamedPipeClientStream pipeClient =
        new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None);
        StreamWriter sw = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                pipeClient.Connect(5000);
                sw = new StreamWriter(pipeClient);
                sw.AutoFlush = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接建立失败,请确保服务端程序已经被打开。");
                this.Close();
            }  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (sw != null)
            {
                sw.WriteLine(this.richTextBox1.Text);
            }
            else
            {
                MessageBox.Show("未建立连接,不能发送消息。");
            }
        }

    #endregion

 

 

 

  #region  服务端



        NamedPipeServerStream pipeServer =
          new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

        private void Form1_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                pipeServer.BeginWaitForConnection((o) =>
                {
                    NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState;
                    pServer.EndWaitForConnection(o);
                    StreamReader sr = new StreamReader(pServer);
                    while (true)
                    {
                        this.Invoke((MethodInvoker)delegate { listView1.Items.Add(sr.ReadLine()); });
                    }
                }, pipeServer);
            });
        }


        #endregion

以上是关于C# 两个进程之间通讯(管道通信 )的主要内容,如果未能解决你的问题,请参考以下文章

13.无名管道通讯编程

Linux 进程间通信-管道

管道通信,王明学learn

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

.Net 进程间通信

c - 使用管道在两个子进程之间持续通信