c#NamedPipe命名管道通信例子

服务端

 private NamedPipeServerStream pipeServer;
        private Thread receiveDataThread = null;
        public fServer()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            receiveDataThread = new Thread(ReceiveDataFromClient) {IsBackground = true};
            receiveDataThread.Start();
        }
        private void ReceiveDataFromClient()
        {
            while (true)
            {
                pipeServer = new NamedPipeServerStream("Server", PipeDirection.InOut, 10);
                pipeServer.WaitForConnection(); 
                StreamReader sr = new StreamReader(pipeServer);
                string jsonData = sr.ReadLine();
                this.Invoke(new EventHandler(delegate
                {
                    this.tblRecMsg.Text = jsonData+DateTime.Now;
                }));
                sr.Close();
            }
        }

客户端

   private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var str = txtSendMsg.Text;
                using (NamedPipeClientStream pipeClient =new NamedPipeClientStream(".", "Server", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None))
                {
                    pipeClient.Connect();
                    //发送
                    using (StreamWriter sw = new StreamWriter(pipeClient))
                    {
                        sw.WriteLine(str);
                        sw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
原文地址:https://www.cnblogs.com/simadi/p/9687133.html