110,538
社区成员
发帖
与我相关
我的任务
分享
//服务端向客户端发送
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;
}
}
//客户端从服务端接收数据
private void button4_Click(object sender, EventArgs e)
{
ReceiveData = new Thread(new ThreadStart(new MyDelegate(ReceiveDataFromServerAllways)));
ReceiveData.Start();
}
private void ReceiveDataFromServerAllways()
{
while (true)
{
Application.DoEvents();
if (tag == 1)
{
tag = 0;
break;
}
try
{
pipeClientA = new NamedPipeClientStream(@"\\.", "testpipe",
PipeDirection.InOut, PipeOptions.None,
TokenImpersonationLevel.Impersonation);
pipeClientA.Connect();//等待?
if (pipeClientA.IsConnected)
{
this.listBox1.Items.Add("成功与服务器连接^_^");
Thread.Sleep(2000);
StreamReader sr = new StreamReader(pipeClientA);
string recData = sr.ReadLine();
if (recData != null)
{
this.listBox1.Items.Add(recData);
}
sr.Close();
}
}
catch (Exception error)
{
this.listBox1.Items.Add(error.Message + "读取数据过程出错!");
}
}
}