### Daytime.5 - A synchronous UDP daytime server

This tutorial program shows how to use asio to implement a server application with UDP.

    int main()
    {
      try
      {
        asio::io_service io_service;

Create an asio::ip::udp::socket object to receive requests on UDP port 13.

        udp::socket socket(io_service, udp::endpoint(udp::v4(), 13));

Wait for a client to initiate contact with us. The remote_endpoint object will be populated by asio::ip::udp::socket::receive_from().

        for (;;)
        {
          boost::array<char, 1> recv_buf;
          udp::endpoint remote_endpoint;
          asio::error_code error;
          socket.receive_from(asio::buffer(recv_buf),
              remote_endpoint, 0, error);

          if (error && error != asio::error::message_size)
            throw asio::system_error(error);

Determine what we are going to send back to the client.

          std::string message = make_daytime_string();

Send the response to the remote_endpoint.

          asio::error_code ignored_error;
          socket.send_to(asio::buffer(message),
              remote_endpoint, 0, ignored_error);
        }
      }

Finally, handle any exceptions.

      catch (std::exception& e)
      {
        std::cerr << e.what() << std::endl;
      }

      return 0;
    }

See the full source listing

Return to the tutorial index

Previous: Daytime.4 - A synchronous UDP daytime client

Next: Daytime.6 - An asynchronous UDP daytime server