...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
This tutorial program shows how to use asio to implement a client application with UDP.
#include <iostream> #include <boost/array.hpp> #include <boost/asio.hpp> using boost::asio::ip::udp;
The start of the application is essentially the same as for the TCP daytime client.
We use an ip::udp::resolver object to find the correct remote endpoint to use based on the host and service names. The query is restricted to return only IPv4 endpoints by the ip::udp::v4() argument.
The ip::udp::resolver::resolve() function is guaranteed to return at least one endpoint in the list if it does not fail. This means it is safe to dereference the return value directly.
Since UDP is datagram-oriented, we will not be using a stream socket. Create an ip::udp::socket and initiate contact with the remote endpoint.
Now we need to be ready to accept whatever the server sends back to us. The endpoint on our side that receives the server's response will be initialised by ip::udp::socket::receive_from().
Finally, handle any exceptions that may have been thrown.
See the full source listing
Return to the tutorial index