Hi. I need to write a mobile app (Xamarin) to send a UDP broadcast, then have a desktop app (WPF/WinForms) listen to the UDP broadcast. I got the sample from the link below, but it is not working. The Xamarin app seems okay (on a Samsung phone), but the desktop app never gets past the "listener.Receive(ref ...)" statement. I would appreciate help. Thanks.
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/using-udp-services
Xamarin Server:
private void StartUdpDiscovery()
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse("192.168.1.255");
//byte[] sendbuf = Encoding.ASCII.GetBytes(args[0]);
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
byte[] data = new byte[2]; //broadcast data
data[0] = 0x0A;
data[1] = 0x60;
s.SendTo(data, ep);
Console.WriteLine("Message sent to the broadcast address");
}
Desktop Client/Listener:
private void StartUdpListener()
{
UdpClient listener = new UdpClient(listenPort);
//IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("192.168.1.255"), listenPort);
try
{
while (true)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP); // NOTE: THE DEBUGGER STALLS HERE AND NEVER MOVES ON...
Console.WriteLine($"Received broadcast from {groupEP} :");
Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
}
catch (SocketException e)
{
Console.WriteLine(e);
}
finally
{
listener.Close();
}
}