UdpClient类使用

UdpCLient类使用

说明: 本文摘录自MSDN UdpClient类
有删减,将常使用的方法列出

构造函数

名称说明
UdpClient()初始化 UdpClient 类的新实例
UdpClient(Int32)新实例初始化 UdpClient 类,并将其绑定到提供的本地端口号。
UdpClient(IPEndPoint)初始化 UdpClient 类的新实例,并将其绑定到指定的本地终结点。
UdpClient(String, Int32)新实例初始化 UdpClient 类,并建立默认远程主机。

方法

名称说明
Connect(IPAddress, Int32)建立默认远程主机使用指定的 IP 地址和端口号。
Connect(IPEndPoint)建立默认远程主机使用指定的网络终结点。
Connect(String, Int32)建立默认远程主机使用指定主机名和端口号。
Close()关闭 UDP 连接。
Send(Byte[], Int32)将 UDP 数据报发送到远程主机。

通信流程

Created with Raphaël 2.1.0 开始 实例化UdpClient,可绑定到本地端口 获取目标IP地址和端口 Connect() Send() Close() 结束

实例

UdpClient udpClient = new UdpClient(11000);
    try{
         udpClient.Connect("www.contoso.com", 11000);

         // Sends a message to the host to which you have connected.
         Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

         udpClient.Send(sendBytes, sendBytes.Length);

         // Sends a message to a different host using optional hostname and port parameters.
         UdpClient udpClientB = new UdpClient();
         udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);

         //IPEndPoint object will allow us to read datagrams sent from any source.
         IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

         // Blocks until a message returns on this socket from a remote host.
         Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
         string returnData = Encoding.ASCII.GetString(receiveBytes);

         // Uses the IPEndPoint object to determine which of these two hosts responded.
         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());

          udpClient.Close();
          udpClientB.Close();

          }  
       catch (Exception e ) {
                  Console.WriteLine(e.ToString());
        }
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值