在做Socket编程的时候碰到这样一个问题,大意是这样的,客户端发一个请求给服务器,服务器要在一定的时间返回东西,否则报错。
下面是大概的代码,      
      public void send()//客户端的发送方法
            {
                try
                {
                    IPEndPoint server = new IPEndPoint(IPAddress.Parse(serverip), sentport);//serverip服务器ip,sentport 发送端口 测试的时候=10001
                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(DataforSend());//DataforSend()发送的数据,测试的时候是随意的字符
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    s.SendTo(bytes, server);
                    MessageBox.Show("send done");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }            public void  GetUdpData()//客户端接受数据的方法
            {
                int i = 0;
                while (i<500)
              {
                    i++;
                    try
                    {
                        IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Any, listenport);//listenport监听的端口 测试的时候=10000
                        byte[] data = UDP_Server.Receive(ref ServerEndPoint);
                        if (data != null)
                        {
                            string str = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
                            if (str=="1")
                            {
                                flag = true;
                                break;
                            }
                            else
                            {
                                flag = false;
                                break;
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                     MessageBox.Show(ex.ToString());
                    }                }
                flag = false;
                MessageBox.Show("there is something wrong with your net connection!");
                return;
            }
        System.Threading.Thread thelistening;//声明一个线程
        Netpack_login login_check = new Netpack_login();//建立一个对象,这个对象有上面的sent()和GetUdpData()方法
        public void listen()//客户端调用监听的函数
        {
            if (thelistening != null)
                thelistening.Abort();
            try
            {
                thelistening = new Thread(new ThreadStart(login_check.GetUdpData));
                thelistening.Start();
            }
            catch (System.Exception ex)
            {
             MessageBox.Show(ex.ToString());
            }
        }
        public void check()//主要的调用函数
        {
             login_check.send();
             listen();
        }
这样做之后发现,thelistening创建的进程并没有在再次使用thelistening的时候终结,而且这样做也没有达到预期的目标,即在一定的时间没有服务器的回应就报错这一点也没实现。这里到底是什么地方错了?