Daytime.6 异步的 UDP Daytime 服务器

Daytime.6 一个异步的 UDP daytime 服务器 #

原文链接 | 源码链接

主函数 #

int main()
{
  try
  {

创建一个服务器对象接收来自客户端的请求,并运行io_context对象。

    boost::asio::io_context io_context;
    udp_server server(io_context);
    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

udp server类 #

class udp_server
{
public:

该构造函数初始化一个套接字以监听 UDP 的13号端口。

  udp_server(boost::asio::io_context& io_context)
    : socket_(io_context, udp::endpoint(udp::v4(), 13))
  {
    start_receive();
  }

private:
  void start_receive()
  {

ip::udp::socket::async_receive_from() 函数使应用程序在后台监听新的请求。当收到此类请求时,io_context 对象将调用带有两个参数的handle_receive()函数:一个是 boost::system::error_code 类型表示操作是否成功的参数,另一个是size_t类型的指定接收到的字节数的参数bytes_transferred【注:见下下段代码中handle_receive()函数的定义】。

    socket_.async_receive_from(
        boost::asio::buffer(recv_buffer_), remote_endpoint_,
        std::bind(&udp_server::handle_receive, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }

handle_receive()函数将处理客户端的请求。

  void handle_receive(const boost::system::error_code& error,
      std::size_t /*bytes_transferred*/)
  {

error 参数包含了异步操作的结果。因为我们只提供了一个字节的 recv_buffer_ 来接收客户端的请求,如果客户端发送的请求大于这个容量,io_context 对象会返回一个错误。如果出现这种错误,我们可以选择忽略。

    if (!error)
    {

定义要发送的内容:

      std::shared_ptr<std::string> message(
          new std::string(make_daytime_string()));

现在调用 ip::udp::socket::async_send_to() 向客户端发送数据。

      socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
          std::bind(&udp_server::handle_send, this, message,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));

在启动异步操作时,如果使用 std::bind,只需要指定与 handler 参数列表匹配的参数。在这个程序中,两个占位符参数(boost::asio::placeholders::error 和 boost::asio::placeholders::bytes_transferred)可能被移除。【注:即如果handler的声明中不需要这些参数,则可以移除他们】

开始监听下一个客户的请求:

      start_receive();

对于客户端请求的任何进一步操作,之后都是由 handle_send() 负责的。

    }
  }

函数 handle_send() 将在服务请求完成之后被调用。

  void handle_send(std::shared_ptr<std::string> /*message*/,
      const boost::system::error_code& /*error*/,
      std::size_t /*bytes_transferred*/)
  {
  }

  udp::socket socket_;
  udp::endpoint remote_endpoint_;
  std::array<char, 1> recv_buffer_;
};