Simple Wrapper of boost::asio for receiving UDP datagrams
More easily receive UDP Data via boost::asio providing just IP address and port umber.
The boost::asio classes provide a cross platform way to communicate via UDP without having to use the raw socket libraries, however they can be confusing and hard to use do to their designed-in flexibility.
Sometimes I just want to provide an IP address and a port number and just receive messages so I have written a wrapper class called boost_udp_receive_rar which can be found on GitHub here.
It has 4 functions that allow you to receive string or binary messages in a synchronous or asynchronous manner, for example to receive ASCII string data:
#include "boost_udp_send_faf.h" #include <thread> // Setup a receiver, specifying IP address and port // Note the IP address is that of the receiving network // interface. As always with UDP and non-standard ports // check that a firewall isn't blocking data transfer. boost_udp_receive_rar rar("127.0.0.1", 8861); // Receive a datagram synchronously as a string // std::string datagram = rar.receive_sync(); std::count << "received: " << datagram << std::endl; // Asynchronously receive a datagram as a string // // We loop calling receive_async() until it returns // a non-empty string. receive_async() returns quickly // and we can do other work (or other async reads on different // ports) while we wait for somethign to arrive. do { datagram = rar.receive_async(); // Do other stuff // // Better do a little sleep to be nice to the // CPU std::this_thread::sleep_for(std::chrono::milliseconds(100)); } while (datagram.empty()); std::count << "received: " << datagram << std::endl;
For an easier way to send UDP data see: boost_udp_send_faf