UDP communication

We have discussed how to communicate through TCP enough, so it is time to switch to UDP now. UDP is a connectionless protocol, and it is easier to use than TCP. There is a client/server example. Below is client code:

  1. #include <boost/asio.hpp>
  2. #include <iostream>
  3. int main()
  4. {
  5. try
  6. {
  7. boost::asio::io_context io_context;
  8. boost::asio::ip::udp::socket socket{io_context};
  9. socket.open(boost::asio::ip::udp::v4());
  10. socket.send_to(
  11. boost::asio::buffer("Hello world!"),
  12. boost::asio::ip::udp::endpoint{boost::asio::ip::make_address("192.168.35.145"), 3303});
  13. }
  14. catch (std::exception& e)
  15. {
  16. std::cerr << e.what() << '\n';
  17. return -1;
  18. }
  19. return 0;
  20. }

Although there is no need to call socket.connect function, you need call socket.open explicitly. Furthermore, the server’s endpoint needs to be specified when invoking socket.send_to.

Server code is like this:

  1. #include <ctime>
  2. #include <functional>
  3. #include <iostream>
  4. #include <string>
  5. #include <boost/asio.hpp>
  6. int main()
  7. {
  8. try
  9. {
  10. boost::asio::io_context io_context;
  11. for (;;)
  12. {
  13. boost::asio::ip::udp::socket socket(
  14. io_context,
  15. boost::asio::ip::udp::endpoint{boost::asio::ip::udp::v4(), 3303});
  16. boost::asio::ip::udp::endpoint client;
  17. char recv_str[1024] = {};
  18. socket.receive_from(
  19. boost::asio::buffer(recv_str),
  20. client);
  21. std::cout << client << ": " << recv_str << '\n';
  22. }
  23. }
  24. catch (std::exception& e)
  25. {
  26. std::cerr << e.what() << std::endl;
  27. }
  28. return 0;
  29. }

Very easy, isn’t it? Build and run client and server. The following log will be printed on server side:

  1. $ ./server
  2. 10.217.242.21:63838: Hello world!
  3. 10.217.242.21:61259: Hello world!