#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

相关文章:

  • 2021-10-29
  • 2021-12-04
  • 2021-06-07
  • 2022-12-23
  • 2021-08-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-06
  • 2021-05-16
  • 2021-09-14
  • 2021-09-22
  • 2021-11-28
相关资源
相似解决方案