C#使用 UdpClient 类进行简单通信的例子

UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报。 因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一来建立默认远程主机:

  • 使用远程主机名和端口号作为参数创建 UdpClient 类的实例。

  • 创建 UdpClient 类的实例,然后调用 Connect 方法。

可以使用在 UdpClient 中提供的任何一种发送方法将数据发送到远程设备。 使用 Receive 方法可以从远程主机接收数据。

UdpClient 方法还允许发送和接收多路广播数据报。 使用 JoinMulticastGroup 方法可以将 UdpClient 预订给多路广播组。 使用 DropMulticastGroup 方法可以从多路广播组中取消对 UdpClient 的预订。

/// <summary>
/// 客户端
/// </summary>
class UDPSender
{
    static void Main(string[] args)
    {
        //创建一个UdpClient对象,0表示系统自动分配发送端口
        //(若同时在本机运行服务端和客户端,则服务端接收和客户端发送需要使用不同端口,否则两个程序使用同一端口将引发冲突)
        UdpClient udpSender = new UdpClient(0);

        //连接到服务端并指定接收端口
        udpSender.Connect("localhost", 11000);

        //连接到子网广播地址并指定接收端口
        //udpSender.Connect("192.168.1.255", 11000);
        //(在使用TCP/IP协议的网络中,主机标识段全为1的IP地址为广播地址,广播地址传送给主机标识段所涉及的所有计算机。
        //例如,对于192.168.1.0(255.255.255.0)网段,其广播地址为192.168.1.255(255的2进制即为11111111),
        //当发出目的地址为192.168.1.255时,它将分发给该网段上的所有计算机。)

        //把消息转换成字节流发送到服务端
        byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
        udpSender.Send(sendBytes, sendBytes.Length);

        //关闭链接
        udpSender.Close();
    }
}
/// <summary>
/// 服务端
/// </summary>
class UDPReceive
{
    static void Main(string[] args)
    {
        //创建一个UdpClient对象,11000为接收端口
        UdpClient udpReceive = new UdpClient(11000);

        //设置远程主机,(IPAddress.Any, 0)代表接收所有IP所有端口发送的数据
        IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);//或 IPEndPoint remoteIpEndPoint = null;

        //监听数据,接收到数据后,把数据转换成字符串并输出
        byte[] receiveBytes = udpReceive.Receive(ref remoteIpEndPoint);
        string returnData = Encoding.ASCII.GetString(receiveBytes);
        Console.WriteLine("This is the message you received " + returnData.ToString());
        Console.WriteLine("This message was sent from " + remoteIpEndPoint.Address.ToString() + " on their port number " + remoteIpEndPoint.Port.ToString());
            
        //关闭连接
        udpReceive.Close();
    }
}

备注:需要先运行服务端,再运行客户端。否则客户端在服务端运行之前就已经发出数据,则服务端不会接收到数据。


下面是使用 UdpClient 类进行多路广播组的简单例子,加入相同的广播组地址即可实现多播。多路广播地址的范围从 224.0.0.0 到 239.255.255.255 ,服务端和客户端使用同一广播地址即可实现多播。


/// <summary>
/// 多路广播组客户端
/// </summary>
class MulticastGroupClient
{
    static void Main(string[] args)
    {
        //创建一个UdpClient对象,0表示系统自动分配发送端口
        var client = new UdpClient(0);

        //将广播地址添加到多路广播组,生存期(路由器跳数)为10
        var ip = IPAddress.Parse("234.56.78.90");
        client.JoinMulticastGroup(ip, 10);

        //定义终结点(服务端IP和接收端口),把消息转换成字节流后发送到服务端
        var multicast = new IPEndPoint(ip, 7788);
        byte[] bytes = Encoding.ASCII.GetBytes("Hello from multicast.");
        client.Send(bytes, bytes.Length, multicast);
    }
}
/// <summary>
/// 多路广播组服务端
/// </summary>
class MulticastGroupServer
{
    static void Main(string[] args)
    {
        //创建一个UdpClient对象,7788为接收端口
        var client = new UdpClient(7788);

        //将广播地址添加到多路广播组,生存期(路由器跳数)为10
        var ip = IPAddress.Parse("234.56.78.90");
        client.JoinMulticastGroup(ip, 10);

        //设置远程主机,(IPAddress.Any, 0)代表接收所有IP所有端口发送的数据
        var multicast = new IPEndPoint(IPAddress.Any, 0);//或 IPEndPoint multicast = null;

        //监听数据,接收到数据后,把数据转换成字符串并输出
        byte[] bytes = client.Receive(ref multicast);
        string msg = Encoding.ASCII.GetString(bytes);
        Console.WriteLine(msg);
    }
}