Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Tuesday, November 13, 2007

My good deed for today - UdpClient in C# joining a multicast group

Why are simple things so difficult! I spent a couple hours banging my head against the wall on this one. All I wanted to do was push out multicast UDP packets and pick them up from a C# program. The UdpClient is not very well documented, and the examples I found didn't work. So simply, this is what I had to do, marked in red. Now this works!

I hope I saved someone a minor headache.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace UbiSenseUdpClientTest
{
class UbiSenseUdpListener
{
private static readonly IPAddress GroupAddress =
IPAddress.Parse("224.237.248.237");
private const int GroupPort = 64555;

private static void StartListener()
{
bool done = false;

UdpClient listener = new UdpClient(GroupPort); <- even though the samples show the noargs constructor for UdpClient, you must specify the port you are going to use if you want to receive multicast packets
IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);

try
{
listener.JoinMulticastGroup(GroupAddress);
//listener.Connect(groupEP); <--- even thought the MSDN examples say to connect, don't connect before you receive, or you will sit and block at the receive below 'waiting for broadcast' below

while (!done)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);

Console.WriteLine("Received broadcast from {0} :\n {1}\n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}

listener.Close();

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}

}

static void Main(string[] args)
{
StartListener();
}
}
}