UdpClient类客户端和服务端demo

服务端demo

static IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
static UdpClient udp = new UdpClient(9999);
static void Main(string[] args)
{
    try
    {
        udp.BeginReceive(MyAsyncCallBack, udp);

        Console.ReadKey();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        udp.Close();
    }
}

static void MyAsyncCallBack(IAsyncResult iar)
{
    UdpClient client = iar.AsyncState as UdpClient;
    if (client.Client == null)
    {
        return;
    }
    if (null != client)
    {
        byte[] buffer = client.EndReceive(iar, ref ipe);
        string result = Encoding.UTF8.GetString(buffer);
        Console.WriteLine("收到数据:" + result);
    }

    client.BeginReceive(MyAsyncCallBack, client);
}

客户端demo

class Program
{
    static void Main(string[] args)
    {
        IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9999);
        using (UdpClient client = new UdpClient())
        {
            byte[] bytes = Encoding.UTF8.GetBytes("Current time:"+DateTime.Now.ToShortTimeString());
            
            //发送3次
            for (int i = 0; i < 3; i++)
            {
                client.Send(bytes, bytes.Length, ipe);
                Thread.Sleep(1000);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/liuguangyin/p/6500674.html