Saturday, January 5, 2019

UDP Broadcasting Sample

Overview

Every year or so I have to use the UdpClient class to perform simple broadcasting and receiving, and I forgot how to do it. There are lots of combinations of parameters that don't work or produce unhelpful crashes if you get them wrong.

The scenario I'm describing is one of the simplest usages of UDP possible, with complete decoupling of the broadcasters and receivers, only sharing knowledge of a common address and port to use. One app broadcasts messages with no idea who is receiving. Other app(s) within range receive the messages. This is ideal for non-critical communication. For example, an app could broadcast a string of XML to say "customer X has been updated", then receivers could refresh their UIs.

For the sanity of myself and others I have composed a small reference DOS command that implements the usage scenario I have just described. It can be launched to either broadcast or receive UDP message strings. Broadcasting and receiving can run on the same machine or on different machines in a network. The UdpClient class is used in the simplest way I think is possible with minimum code.

Run the command as udpdemo broadcast and it enters a broadcast prompt loop.

Run the command as udpdemo receive and it enters a receive loop.

Extra instructions are displayed on how to tell each loop to gracefully end.

For simplicity, the command uses hard-coded multicast address 227.7.7.7 and port 54777. For more general information run a web search for "multicast address range".

The complete C# source code for the DOS command can be found HERE (as a txt file). The following image shows the demo command running as a broadcaster and a receiver and sending two messages, the last one "end" tells the receiver to close.

Notes

Although using UDP in the way I have in the sample is simple to code and understand, remember that it is connectionless and has no built-in reliability. If messages are blocked by some network rules or receivers are not running, then messages may be silently lost, if that matters in your usage scenario.

A modern alternative to UDP broadcasting may be to use queues. For .NET developers, using Azure Queue storage requires little code, it's really fast, the capacity is enormous and it's dirt cheap. For more sophisticated scenarios there are products like Event Hubs, Service Bus and more. Queues are better than UDP if you don't want messages to be lost.