One of the great strengths of UDP (User Datagram Protocol) is broadcasting. This feature allows a single sent packet (datagram) to be to received by multiple peers on the same network. The alternative would be an independent send for each desired destination. The following scenarios are several examples when you might consider using UDP broadcasts:

  • Checking which network peers might be online before establishing more robust, .e.g TCP (Transmission Control Protocol), connections. Also known as Peer Discovery.
  • Informing networked peers of a newly available service.
  • Delivering the same, continuously updated, information to a group of peers.

The following short example demonstrates how to easily setup UDP broadcasting using NetworkComms.Net.

To send a UDP broadcast packet:

UDPConnection.SendObject("ChatMessage", "This is the broadcast test message!", 
new IPEndPoint(IPAddress.Broadcast, 10000));

To receive UDP broadcast packets the configuration is exactly the same as for any other connection type:
//We need to define what happens when packets are received.
//To do this we add an incoming packet handler for a 'ChatMessage' packet type. 
//
//We will define what we want the handler to do inline by using a lambda expression
//http://msdn.microsoft.com/en-us/library/bb397687.aspx.
//We could also just point the AppendGlobalIncomingPacketHandler method 
//to a standard method (See AdvancedSend example)
//
//This handler will convert the incoming raw bytes into a string (this is what 
//the <string> bit means) and then write that string to the local console window.
NetworkComms.AppendGlobalIncomingPacketHandler<string>("ChatMessage", 
    (packetHeader, connection, incomingString) => 
    { 
        Console.WriteLine("\n  ... Incoming message from " + 
            connection.ToString() + " saying '" + 
            incomingString + "'."); 
    });

//Start listening for incoming UDP data
Connection.StartListening(ConnectionType.UDP, new IPEndPoint(IPAddress.Any, 10000));

We hoped you enjoyed this short tutorial, demonstrating how to send UDP broadcasts using NetworkComms.Net. If you have any feedback or questions please post a comment here or on our forums.