I have the following code that sends a multicast message then waits for a response to be sent to the address the message came from. If I watch the traffic in Wireshark I can see the message sends ok and a response comes back to the correct IP and port however the socket never returns from the receive line, it’s like the response is not being picked up.
var multicastAddress = IPAddress.Parse("239.255.255.250");
var multicastPort = 1900;
var unicastPort = 1901;
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.Bind(new IPEndPoint(IPAddress.Any, unicastPort));
socket.Connect(new IPEndPoint(multicastAddress, multicastPort));
var thd = new Thread(() =>
{
try
{
while (true)
{
var response = new byte[8000];
EndPoint ep = new IPEndPoint(IPAddress.Any, unicastPort);
socket.ReceiveFrom(response, ref ep);
var str = Encoding.UTF8.GetString(response);
Devices.Add(new SsdpDevice() {Location = str});
}
}
catch
{
//TODO handle exception for when connection closes
}
});
socket.Send(broadcastMessage, 0, broadcastMessage.Length, SocketFlags.None);
thd.Start();
Thread.Sleep(30000);
socket.Close();
}
I know I should be using the asynchronous methods on the socket class and need stop relying on Thread.Sleep but I just want to get a simple example working before I tidy up the code.
Gavin, check this out:
Connect(), multicast is connectionless messaging (just as broadcast is).Bind().SendTo()instead ofSend(), which won’t work in this case.And a simple working example: