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();
}
}
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000);
can just beIPEndPoint ip = null;
- it's not a struct. Its use in theEndReceive()
method is to define the sender. Populating it with anything at all is a bit misleading. – maxp