简体   繁体   English

C#我怎么知道是否发送了UDP数据包?

[英]C# how i can know if a UDP packet sent or not?

i'm using this code 我正在使用此代码

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

so how i can know if "Hello" sent and received or not because all results always return 17 所以我怎么知道是否发送和接收“ Hello”,因为所有结果总是返回17

UDP does not implement an acknowledgement segment like TCP or other protocols. UDP不像TCP或其他协议那样实现确认段。

UdpClient.Send() sends datagrams to the specified endpoint and returns the number of bytes successfully sent. UdpClient.Send()将数据报发送到指定的端点,并返回成功发送的字节数。

Thus, the 17 that you are seeing in res is telling you that 17 bytes have successfully been sent. 因此,您所看到的17个 res是告诉你,17个字节已成功发送。

Source: https://msdn.microsoft.com/en-us/library/82dxxas0(v=vs.110).aspx 来源: https : //msdn.microsoft.com/zh-cn/library/82dxxas0(v=vs.110).aspx

UDP is a connectionless protocol so there is no gurantee that the data was sent to its receipient. UDP是无连接协议,因此不保证数据已发送到其收件人。

One simple way to confirm that the data was indeed sent is to have the remote host send back an ack (acknowledgement) to the server. 确认数据确实已发送的一种简单方法是让远程主机将确认(确认)发送回服务器。

Here is a simple implementation you can find from MSDN 这是一个简单的实现,您可以从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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM