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

2019-12-30 15:08:31王振洲

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();
  }
}