I have an application which implements an autodiscovery mechanism and I'm having an issue with the UdpClient. It works fine as long as a single instance of the application is open. However, when a second instance is open only the first receives the unicast packets. Interestingly enough, a similar application that implements the same mechanism doesn't seem to have this issue. Any suggestions?
class AutoDiscovery
{
private UdpClient Udp;
private IPEndPoint BroadcastEP = new IPEndPoint(IPAddress.Broadcast, 1234);
private List<byte> AutoDiscoverPacket = new List<byte>();
public ObservableCollection<DiscoveredDevice> DiscoveredDevices = new ObservableCollection<DiscoveredDevice>();
public AutoDiscovery()
{
Udp = new UdpClient();
Udp.ExclusiveAddressUse = false;
Udp.EnableBroadcast = true;
Udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Udp.Client.Bind(new IPEndPoint(IPAddress.Any, 1234));
AutoDiscoverPacket.AddRange(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
AutoDiscoverPacket.AddRange(Encoding.ASCII.GetBytes("SomeStaticString"));
while (AutoDiscoverPacket.Count < 123)
{
AutoDiscoverPacket.Add(0x00);
}
ReceiveDataAsync(ReceiveDataCallback);
}
~AutoDiscovery()
{
if (Udp != null)
{
try
{
Udp.Close();
}
finally
{
}
}
}
public void Discover()
{
DiscoveredDevices.Clear();
Udp.Send(AutoDiscoverPacket.ToArray(), AutoDiscoverPacket.Count, BroadcastEP);
}
private void ReceiveDataAsync(Action<UdpReceiveResult> Callback)
{
Task.Run(async () =>
{
try
{
while (true)
{
//IPEndPoint object will allow us to read datagrams sent from any source.
UdpReceiveResult receivedResults = await Udp.ReceiveAsync();
Callback(receivedResults);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
});
}
private void ReceiveDataCallback(UdpReceiveResult Result)
{
// Do stuff here
}
}
}