简体   繁体   English

在boost :: asio中,为什么异步接受处理程序需要重启异步接受?

[英]In boost::asio, why does the asynchronous accept handler need to restart the asynchronous accept?

In the Daytime.3 tutorial for boost::asio (asynchronous TCP server), the class tcp_server contains the following two methods: 在boost :: asio(异步TCP服务器)的Daytime.3教程中,类tcp_server包含以下两种方法:

void start_accept()
{
  tcp_connection::pointer new_connection =
    tcp_connection::create(acceptor_.get_io_service());

  acceptor_.async_accept(new_connection->socket(),
      boost::bind(&tcp_server::handle_accept, this, new_connection,
        boost::asio::placeholders::error));
}

void handle_accept(tcp_connection::pointer new_connection,
    const boost::system::error_code& error)
{
  if (!error) new_connection->start(); // ***

  start_accept();
}

My concern is the line marked *** . 我担心的是标有***的线。 What if this operation takes a long time to complete? 如果此操作需要很长时间才能完成,该怎么办? Even if it doesn't, there must be some time gap between the *** line and the call to start_accept , during which the server will fail to accept incoming connections. 即使没有, ***行和start_accept调用之间也必须有一些时间间隔,在此期间服务器将无法接受传入连接。 Wouldn't it make more sense for async_accept to register an OS handler that doesn't halt when it accepts its first connection? async_accept注册一个在接受第一次连接时不会停止的OS处理程序会不会更有意义? Also, is this a real issue and how would I fix it? 此外,这是一个真正的问题,我将如何解决它?

The server won't "fail to accept incoming connections"; 服务器不会“无法接受传入连接”; that's what the second parameter of the listen() function is for in the sockets API. 这就是套接字API中listen()函数的第二个参数。 But you are correct that the server can have a delay in handling the client request. 但是你是正确的,服务器可以延迟处理客户端请求。 A single-threaded application that requires lots of computation will cause issues, hence why this particular example really only performs IO. 需要大量计算的单线程应用程序将导致问题,因此这个特定示例实际上只执行IO的原因。 If your server really does need to perform something CPU intensive, then the handler should be passed to a task manager of some sort. 如果您的服务器确实需要执行CPU密集型操作,那么应该将处理程序传递给某种类型的任务管理器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM