using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace
udpClient_test
{
    delegate void
MessageReady(object sender, string message);
    class
Program
    {
        static void
Main(string[]
args)
        {
            Receiver
client = new
Receiver();
        }
    }
    class
Receiver
    {
        public MessageReady
MsgRdyDelegage;
        private UdpClient
udpClient;
        private IPEndPoint
remoteEp;
        public
Receiver()
        {
            MsgRdyDelegage
= this.MessageResolve;
            udpClient
= new
UdpClient(new IPEndPoint(IPAddress.Any, 9010));//绑定9010端口
            remoteEp
= new
IPEndPoint(IPAddress.Any, 0);
            udpClient.BeginReceive(this.requestCallback, null);//开始异步接收
        }
        
        private void
MessageResolve(object sender, string
message)
        {
            //这里定义你对接收到的信息的处理,message是接收到的信息,比如:
            Console.WriteLine(message);
            /*
             *
这里添加你的其他逻辑,代码运行时间长点也没关系,不会影响到接收线程,
             *
这是后台线程的方法块,可以通过线程休眠来测试:
             * 
             *
*/

            System.Threading.Thread.Sleep(10000);
        }
        private void
requestCallback(IAsyncResult
ar)
        {
           string message =
Encoding.UTF8.GetString(udpClient.EndReceive(ar, ref
remoteEp));
           //下面采用异步委托,把信息处理转移到后台线程
           MsgRdyDelegage.BeginInvoke(this,message, delegate(IAsyncResult asyncresult)//构造匿名委托
           {
               MessageReady
messageReady = asyncresult.AsyncState as
MessageReady;
               messageReady.EndInvoke(asyncresult);
               udpClient.BeginReceive(this.requestCallback, null);
           },
MsgRdyDelegage);
        }
    }
}