简体   繁体   English

Boost Asio将接受的套接字从一个io_service转移到另一个io_service

[英]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. 我正在编写多线程TCP服务器,根据应用程序设计,我需要每个线程都具有io_service多个线程。

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. 通过这种设计,我需要接受来自一个Thread/io_service连接进行身份验证过程(基于应用程序逻辑),然后将该接受的连接转移到另一Thread/io_service以开始从经过身份验证的连接中读取长数据。

So the question is how transfer accepted connection from one io_service into another one ? 那么问题是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 参见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). 以下是有关如何执行此操作的小演示: switch_io_context_for_socket_main.cpp (使用独立ASIO)。

The key is to use socket::release + socket::assign : 关键是使用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.

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

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