boost::asio 同步服务器在第一个之后不接受连接

Sta*_*ght 1 c++ boost-asio

我正在编写简单的同步 asio 服务器。工作流程如下 - 在无限循环中接受连接并为每个连接创建线程。我知道,这不是那么理想,但异步对我来说太难了。

这是我丑陋的代码:

std::vector<asio::io_service*> ioVec;
std::vector<std::thread*> thVec;
std::vector<CWorker> workerVec;
std::vector<tcp::acceptor*> accVec;

while (true) {
    ioVec.emplace_back(new asio::io_service());
    accVec.emplace_back(new tcp::acceptor(*ioVec.back(), tcp::endpoint(tcp::v4(), 3228)));
    tcp::socket* socket = new tcp::socket(*ioVec.back());
    accVec.back()->accept(*socket);
    workerVec.push_back(CWorker());
    thVec.emplace_back(new std::thread(&CWorker::run, &workerVec.back(), socket));
}
Run Code Online (Sandbox Code Playgroud)

问题是第一次连接完成,它被正确接受,线程被创建,一切都很好。断点在“accept()”字符串上正确触发。但是,如果我想创建第二个连接(第一个连接是否 DCed 无关紧要)-> telnet 已连接,但未触发下一个“接受”字符串上的断点,并且连接没有响应任何内容。

所有这些向量的东西 - 我试图以某种方式调试以创建单独的接受器,任何连接的 io_service - 没有帮助。谁能指出我错误在哪里?

PS 视觉工作室 2013

Dal*_*son 5

基于 asio 的侦听器的一般模式是:

// This only happens once!
create an asio_service
create a socket into which a new connection will be accepted
call asio_service->async_accept passing 
       the accept socket and 
       a handler (function object)  [ see below]
start new threads (if desired.  you can use the main thread if it 
   has nothing else to do)
Each thread should:
    call asio_service->run [or any of the variations -- run_one, poll, etc]

Unless the main thread called asio_service->run() it ends up here 
"immediately"  It should do something to pass the time (like read
from the console or...)   If it doesn't have anything to do, it probably
should have called run() to make itself available in the asio's thread pool.
Run Code Online (Sandbox Code Playgroud)

在处理函数中:

  Do something with the socket that is now connected.
  create a new socket for the next accept
  call asio_service->async_accept passing 
       the new accept socket and 
       the same handler. 
Run Code Online (Sandbox Code Playgroud)

特别要注意的是,每个 accept 调用只接受一个连接,并且在同一端口上一次侦听的次数不应超过一个,因此您需要在上一次调用的处理程序中再次调用 async_accept。

Boost ASIO 有一些非常好的教程示例,比如这个