我有 2 个程序,1 个用于发送 UDP 广播消息,1 个用于侦听此广播。我的问题是,有时当我发送广播时,接收者会收到 2 条消息。为什么?
收货人代码:
public class Receiver {
private readonly UdpClient udp = new UdpClient(15000);
private void StartListening()
{
this.udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
StartListening();
}
}
发件人代码:
public class Sender {
public void Send() {
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);
byte[] bytes = Encoding.ASCII.GetBytes("Foo");
client.Send(bytes, bytes.Length, ip);
client.Close();
}
}