Server Client应用程序

时间:2012-04-02 14:10:37

标签: c# winforms sockets tcp

这是我的服务器代码我遇到问题,因为我的程序冻结了,不知道出了什么问题。

   private void button1_Click(object sender, EventArgs e)
    {
        if (button1.Text == "Listen")
        {
            tcpl = new TcpListener(IPAddress.Any, 5555);
            tcpl.Start();

            try
            { 
                // get random word from text
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Txt |*.txt";
                ofd.Title = "Tekst";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    String[] myString = File.ReadAllLines(ofd.FileName);
                    textBox1.Text = myString[r.Next(myString.Length)];
                }

                    Socket socketForClient = tcpl.AcceptSocket();
                    if (socketForClient.Connected)
                    {
                        MessageBox.Show("Client connected" + socketForClient.RemoteEndPoint.ToString());
                        NetworkStream networkStream = new NetworkStream(socketForClient);
                        StreamWriter sw = new StreamWriter(networkStream);
                        StreamReader sr = new StreamReader(networkStream);
                        string line = sr.ReadLine();
                        richTextBox1.Text = "Accepted: " + line;
                        line = line.ToUpper();
                        sw.WriteLine(line);
                        richTextBox1.Text = "Sended : " + line;
                        sw.Flush();
                    }
                    socketForClient.Close();

            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
            button1.Text = "stop";
        }
        else 
        {
            tcpl.Stop();
            MessageBox.Show("Disconnected");
            button1.Text = "Listen";
        }

我的程序冻结在一行:Socket socketForClient = tcpl.AcceptSocket();而且不知道为什么。我是从学校的一个例子写的。谢谢你的帮助。

1 个答案:

答案 0 :(得分:6)

AcceptSocket()是一个阻止调用,仅在客户端连接后返回。 如果您在UI线程中调用它,UI将冻结。

您需要在后台线程上执行此操作。