2017-02-09 119 views
0

我使用这个代码C#如何知道是否发送UDP数据包?

 bool NotSent = true; 
     while (NotSent) 
     { 
      try 
      { 
       UdpClient udpServer = new UdpClient(port); 
       udpServer.Connect(IPAddress.Parse("192.168.1.66"), port); 
       Byte[] sendBytes = Encoding.ASCII.GetBytes("Hello"); 
       int res = udpServer.Send(sendBytes, sendBytes.Length); 
       MessageBox.Show("Sent : " + res); 
       udpServer.Close(); 
       NotSent = false; 
      } 
      catch (Exception ex) { MessageBox.Show("Error : " + ex.ToString()); continue; } 
     } 

,所以我怎么知道“你好”发送和接收与否,因为所有的结果通常会返回17

回答

0

UDP是无连接协议所以没有出示担保的数据被发送到其RECEIPIENT。

确认数据确实发送的一种简单方法是让远程主机向服务器发回确认(确认)。

下面是一个简单的实现,你可以从MSDN找到

// 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);