码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-09-04 19:54:11      阅读:498      评论:0      收藏:0      [点我收藏+]

标签:reg   建立   连接   line   ken   orm   pipe   readline   ons   

  #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# 两个进程之间通讯(管道通信 )

标签:reg   建立   连接   line   ken   orm   pipe   readline   ons   

原文地址:http://www.cnblogs.com/qc-id-01/p/7474978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!