Reputation: 263
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
Upvotes: 3
Views: 1964
Reputation:
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);
Upvotes: 1
Reputation: 340
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.
Upvotes: 0
Reputation: 6901
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.
Upvotes: 1