On a network messages are normally sent to a specific host (IP, port).
However, UDP (and IP) has the ability to broadcast messages to all host on the local network. Broadcast messages are normally not forwarded to other networks by routers.
Later we will use UDP broadcast when your IoT (Internet of Things) devices will broadcast measurements to hosts on the local network.
But, before we do that you have to practice some simple UDP broadcast programming.
MSDN Using UDP Services has two examples:
Make two separate Visual Studio solutions, one for each program. Run the programs to see if the programs can communicate.
Modify the broadcasting program to keep on broadcasting a message like "The time is " + DateTime.Now
(while (true) ...) every 5 seconds (Thread.Sleep(5000)).
Modify the receiver to use using
, not try ... catch ... finally
The class IPAddress defines the broadcast address IPAddress.BroadCast, i.e. 255.255.255.255.
To use this address the socket must explicitly enable broadcasting socket.EnableBroadcast = true;
Refactor the broadcasting program to use the higher level abstraction UdpClient, not Socket.
Your UDPListener can receive broadcast not only from your sender - but from other sender on the local network.
However, you have to do a few things to make it work:
If may hosts broadcast on the same network using the same port, it is hard for the receiver to know who is the sender. A solution is to use different port numbers, or tag the message with a string identifying the sender.
Is it possible for two (or more) host to broadcast to the same port, on the same network? Try it!
Now you are ready to listen for UDP broadcasts from our local IoT devices.
Listen on port 7000 on the network EGV5-DMU.
You will (if the broadcast process runs) receive the latest measurements from your local IoT devices, including the temperature, etc.
Make a program which will keep reading (while (true) ...) the broadcasts, and calculate the average temperature, and some other statistics.