Overview
The code in this sample was eventually included in the Orthogonal.MixedCommsLib library and NuGet package. The library contains two pairs of UDP client-server classes, one pair for one-way broadcasting as described in the post below, and other pair for discovery (similar to the way SQL Server Studio can find SQL Instances).
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.
