boost::asio sync server 在第一个连接后不接受连接



我正在编写简单的同步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));
}

问题是第一个连接正在完成,它被正确接受,线程被创建,一切都很好。断点在"accept()"字符串上正确触发。但是如果我想创建第二个连接(第一个是否为 DCed 并不重要)-> telnet 已连接,但不会触发下一个字符串上的断点"接受",并且连接没有响应任何东西。

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

附言视觉工作室 2013

基于 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.

在处理程序函数中:

  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. 

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

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

最新更新