Multicasting with UDP Packets


The UDPClient can be easily configured to broadcast to a multicast IP address or to receive packets from a multicast IP address. A multicast IP address is operated by a server that maintains a list of multicast subscribers. When a packet is sent to a multicast IP address, the server sends a copy of the packet to the IP address of every client who has subscribed.

Sending Multicast Packets

To send UDP packets to a multicast IP address, no special action is required. Simply send your packets as shown in the sample code from the earlier section "Writing Code for UdpClient," but choose a multicast IP address as the destination for the packets.

Receiving Multicast Packets

To receive multicast packets, you must first subscribe with the server that is operating the multicast IP address. Once you have subscribed to the multicast IP address, you can listen for packets from the multicast IP address in the same way as for any other address, as shown in the section "Writing Code for UdpClient." When someone sends a packet to the multicast IP address, the server forwards it to everyone on the subscriber list, including you. To subscribe to a multicast IP address, follow these steps:

  1. Create an IPAddress instance that points to the multicast IP address.

  2. Call UdpClient.JoinMultiCastGroup() , passing the IPAddress as an argument.

Future attempts to receive from the multicast IP address will receive forwarded packets from the multicast server. Here are the JoinMultiCastGroup overloads supported on the .NET Compact Framework:

JoinMultiCastGroup(IPAddress multicastAddr) Joins a multicast group at multicastAddr

JoinMultiCastGroup(IPAddress multicastAddr, int maxHops) Joins a multicast group at multicastAddr but receives only packets that have made up to maxHops total travel hops

Here is an example of the code:

 
 C# IPAddress l_multicastAddress = new IPAddress("172.68.0.22"); // Only receive multicast packets that have traveled // for 40 or less hops l_UDPClient.JoinMulticastGroup(l_multicastAddress, 40); VB IPAddress l_multicastAddress = new IPAddress("172.68.0.22") ' Only receive multicast packets that have traveled ' for 40 or less hops l_UDPClient.JoinMulticastGroup(l_multicastAddress, 40); 

To unsubscribe from a multicast IP address, call UDPClient.DropMulticastGroup() as follows :

 
 C# l_UDPClient.DropMulticastGroup(l_multicastAddress); VB l_UDPClient.DropMulticastGroup(l_multicastAddress) 


Microsoft.NET Compact Framework Kick Start
Microsoft .NET Compact Framework Kick Start
ISBN: 0672325705
EAN: 2147483647
Year: 2003
Pages: 206

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net