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

猜你喜欢

转载自blog.csdn.net/Tokeyman/article/details/51437111
今日推荐