I'm working on a UWP/Xamarin.Android app that uses SSDP multicast search to detect other devices on the local network that are running the same app. I've been able to send out multicast messages with UdpClient, but I'm not able to receive multicast messages. It hangs on UdpClient.ReveiveAsync()
and never receives a message. Any help in getting this to work would be greatly appreciated.
Here's the coding I'm using to initialize the UdpClient and receive messages:
protected override Task CreateResourcesAsync()
{
address = IPAddress.Parse(Settings.Address ?? "239.255.255.250");
port = Settings.Port ?? 1900;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
client = new UdpClient() { MulticastLoopback = true };
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// This line was to test setting SO_REUSE_MULTICASTPORT on Windows, it didn't help
//client.Client.SetSocketOption(SocketOptionLevel.Socket, (SocketOptionName)0x3008, true);
client.Client.Bind(localEndPoint);
client.JoinMulticastGroup(address);
Task.Run(ReceiveThread);
return Task.CompletedTask;
}
async Task ReceiveThread()
{
while (IsActive && client != null)
{
// Does not receive any messages so the Task returned from client.ReceiveAsync() does not complete
UdpReceiveResult request = await client.ReceiveAsync();
}
}
I've tried using different multicast addresses and ports other than the SSDP ones, I've also tried binding to both IPAddress.Any
and my local IP address, but neither works.
I'm able to receive multicast messages using the WinRT DatagramSocket
, but I can't continue to use WinRT as the app needs to run on Android. I'll include my DatagramSocket
code just in case it can be used to help somehow:
DatagramSocket socket = new DatagramSocket();
// If MulticastOnly is not true, it will bind to the port but won't receive messages
socket.Control.MulticastOnly = true;
socket.MessageReceived += async (sender, args) =>
{
// Immediately receives SSDP search requests from various devices on my network
};
await socket.BindServiceNameAsync("1900");
socket.JoinMulticastGroup("239.255.255.250");