我有这段代码,这是一个简单的WPF TcpListener应用程序。下面的代码工作正常。 但是当我在void Client()中添加代码到Button_Click()事件时,它不起作用!我不明白这个的原因。 有人可以向我解释一下吗?。
此代码运行良好:
TcpClient client;
NetworkStream ns;
BinaryReader bRead;
BinaryWriter bWrite;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Task t = new Task(new Action(() =>
{
Server();
}));
t.Start();
Thread.Sleep(100);
Client();
}
public void Client()
{
client = new TcpClient(Dns.GetHostName(), 2055);
ns = client.GetStream();
bRead = new BinaryReader(ns);
bWrite = new BinaryWriter(ns);
bWrite.Write("entered");
bWrite.Flush();
bWrite.Write("entered");
bWrite.Flush();
}
public void Server()
{
TcpListener listener = new TcpListener(2055);
listener.Start();
TcpClient CL = listener.AcceptTcpClient();
NetworkStream ns = CL.GetStream();
BinaryReader bread = new BinaryReader(ns);
BinaryWriter bwrite = new BinaryWriter(ns);
while(true)
{
MessageBox.Show("waiting...");
string res = bread.ReadString();
MessageBox.Show(res);
}
}
单击按钮Button_click()时,此代码无响应:
TcpClient client;
NetworkStream ns;
BinaryReader bRead;
BinaryWriter bWrite;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Task t = new Task(new Action(() =>
{
Server();
}));
t.Start();
Thread.Sleep(100);
Client();
}
public void Client()
{
}
public void Server()
{
TcpListener listener = new TcpListener(2055);
listener.Start();
TcpClient CL = listener.AcceptTcpClient();
NetworkStream ns = CL.GetStream();
BinaryReader bread = new BinaryReader(ns);
BinaryWriter bwrite = new BinaryWriter(ns);
while(true)
{
MessageBox.Show("waiting...");
string res = bread.ReadString();
MessageBox.Show(res);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
client = new TcpClient(Dns.GetHostName(), 2055);
ns = client.GetStream();
bRead = new BinaryReader(ns);
bWrite = new BinaryWriter(ns);
bWrite.Write("entered");
bWrite.Flush();
bWrite.Write("entered");
bWrite.Flush();
}