Search code examples
c++boost

why my app based on boost::asio didn't accept new connection


I write a test app which creates 2,000 connections to my tcp server. After kill/start my test app a few times, my tcp server cannot accept new connection anymore? I have no idea of debugging this problem, any suggestion? Some code snippet lists below:

 Server(io_service& s, tcp::endpoint const& listen_endpoint, size_t thread_number):io_(s),
signals_(s),
acceptor_(io_, listen_endpoint),
thread_pool_size_(thread_number) {
  signals_.add(SIGINT);
  signals_.add(SIGTERM);
  signals_.async_wait(bind(&Server::Stop, this));
  shared_ptr<ClientType> c(new ClientType(io_));

  acceptor_.async_accept(c->socket, bind(&Server::AfterAccept, this, c, _1));

  //launch thread to preapre message
  MessageThread d;
  MyApp& app = AppHolder::Instance();
  d.support_text_message = app.config().support_text_message;
  d.support_digit_message = app.config().support_digit_message;
  d.interval = app.config().interval;
  boost::thread thrd1(d);
}

  void AfterAccept(shared_ptr<ClientType>& c, error_code const& ec) {
    // Check whether the server was stopped by a signal before this completion
    // handler had a chance to run.
    if (!acceptor_.is_open()) {
      BOOSTER_INFO("Server") << "thread id: " << this_thread::get_id() << " acceptor is closed";
      return;
    }

    if (!ec) {
      c->StartJob();
      shared_ptr<ClientType> c2(new ClientType(io_));
      acceptor_.async_accept(c2->socket, bind(&Server::AfterAccept, this, c2, _1));
    }
  }

Solution

  • Before the call to acceptor_.async_accept try adding the line:

    acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));