2017-02-09 117 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);