UdpClient无法使用ReceiveTimeout来使用BeginReceive

时间:2014-05-15 22:00:00

标签: c# .net udp udpclient

该方法以调用ReceiveAuthPacket开始,我非常希望它监听数据包3秒然后关闭...我试图用" u.Client.ReceieveTimeout = 3000"但那不起作用......任何想法?

        private void ReceiveAuthPacket()
        {
            IPEndPoint e = new IPEndPoint(IPAddress.Any, 5001);
            UdpClient u = new UdpClient(e);

            UdpState s = new UdpState();
            s.E = e;
            s.U = u;

            Console.WriteLine("Listening for Messages: ");
            u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).U;
            IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).E;
            u.Client.ReceiveTimeout = 3000;

            Byte[] receiveBytes = u.EndReceive(ar, ref e);
            string receiveString = Encoding.ASCII.GetString(receiveBytes);

            Console.WriteLine("Received: {0}", receiveString);
            MessageReceived = true;

            string errMsg = "";
            if (AuthMessageParser.ParseMessage(receiveString, ref errMsg))
                Authenticated = true;
            else
            {
                ErrorMessage += errMsg;
                Authenticated = false;
            }
        }

0 个答案:

没有答案