简体   繁体   中英

Boost Asio transfer accepted socket from one io_service to another io_service

I'm writing multithreaded TCP server, where based on application design I need to have multiple threads with io_service for each one.

With that design I need to accept connection from one Thread/io_service make an authentication process (based on application logic) and then transfer that accepted connection to another Thread/io_service to start reading long data from authenticated connection.

So the question is how transfer accepted connection from one io_service into another one ?

Is there any standard functionality for this ?

Thanks

Going to answer based on a general idea. Pseudo code for that:

create_io_service_pool(...);
tcp::acceptor tcp_acceptor(accept_io_service, tcp::endpoint(tcp::v4(), 6069));
while (true) {
  auto csocket = tcp::socket(get_io_service_from_pool());
  tcp_acceptor.accept(csocket);
  /// Any async operation afterwords on csocket would be handled by the 
  /// io_service it got from `get_io_service_from_pool` function
  /// which you can design as you wish..may be round-robin one for simplicity
}

I am just hoping that this is what you were looking for.

See http://think-async.com/Asio/asio-1.12.2/doc/asio/reference/basic_socket_acceptor/async_accept/overload4.html

void accept_handler(const asio::error_code& error,
    asio::ip::tcp::socket peer)
{
  if (!error)
  {
    // Accept succeeded.
  }
}

...

asio::ip::tcp::acceptor acceptor(io_context);
...
acceptor.async_accept(io_context2, accept_handler);

Here is a small demo of how you can do it: switch_io_context_for_socket_main.cpp (using standalone ASIO).

The key is to use socket::release + socket::assign :

tcp::socket sock1{ primary_io_context };
// ... accept/connect/do something with it 

// Switch it to another context:
tcp::socket sock2{ another_io_context };
sock2.assign( tcp::v4(), socket1.release() );

// work with sock2 which is bind to another context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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