0

我有这段代码,这是一个简单的 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();
    }
4

0 回答 0