C#如何知道是否发送UDP数据包?
问题描述:
我使用这个代码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
答
UDP未实现的确认段,如TCP或其他协议。
UdpClient.Send()
发送数据报到指定端点和 返回成功发送的字节数。
因此,您看到在res
告诉你已成功发送的17个字节。
来源:https://msdn.microsoft.com/en-us/library/82dxxas0(v=vs.110).aspx
答
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);
现在明白了,谢谢彼得 –