Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c# - Sending UDP broadcast, receiving multiple messages

I've got 2 programs, 1 for sending an UDP broadcast message and 1 that is listening for this broadcast. My problem is that sometimes when I send a broadcast, the receiver receives 2 messages. Why?

Receiver code:

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

Sender code:

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();
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strictly speaking, packet duplication in IP network is allowed behavior of the network and you have to be able to deal with it in your software even if you will somehow get rid of it this time. If you are just wondering about why this happens in your particular case... at a first glance I see nothing wrong with your code. Do you have several IP addresses on Ethernet port of your computer or some such? I think wireshark might help get more details about what's going on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...