日期:2014-05-18 浏览次数:21058 次
//服务端向客户端发送 private void button1_Click(object sender, EventArgs e) { Thread SendData=new Thread(new ThreadStart(WriteData)); SendData.Start(); } private void WriteData() { try { this.listBox1.Items.Add("开始连接管道……"); pipeServer =new NamedPipeServerStream("testpipe", PipeDirection.InOut, 2); pipeServer.WaitForConnection(); Thread.Sleep(1000); if (pipeServer.IsConnected) { this.listBox1.Items.Add("与客户端连接成功^_^"); StreamWriter sw = new StreamWriter(pipeServer); sw.WriteLine(this.textBox1.Text); sw.Flush(); Thread.Sleep(1000); sw.Close(); } else { this.listBox1.Items.Add("与客户端连接失败(⊙_⊙)"); } } catch (Exception error) { this.listBox1.Items.Add(error.Message + "写数据时发生错误!"); } } //服务端从客户端接收数据 private void button2_Click(object sender, EventArgs e) { ReceiveDataThread = new Thread(new ThreadStart(ReceiveDataFromClient)); ReceiveDataThread.Start(); } private void ReceiveDataFromClient() { while (true) { try { pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 2); pipeServer.WaitForConnection();//等待 StreamReader sr = new StreamReader(pipeServer); string recData = sr.ReadLine(); this.listBox1.Items.Add(recData); Thread.Sleep(1000); sr.Close(); } catch (Exception) { throw; } if (tag==1) { break; } } }
//客户端向服务端发数据 private void button1_Click(object sender, EventArgs e) { Thread WriteData = new Thread(new ThreadStart(SendData)); WriteData.Start(); } private void SendData() { try { pipeClientA = new NamedPipeClientStream(@"\\.", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); pipeClientA.Connect(); StreamWriter sw = new StreamWriter(pipeClientA); sw.WriteLine(this.textBox1.Text); sw.Flush(); Thread.Sleep(1000); sw.Close(); } catch (Exception) { throw; } }