我正在编写简单的同步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则无关紧要) - &gt; telnet已连接,但未触发下一个“accept”字符串上的断点,并且连接没有响应任何内容。
所有这些向量的东西 - 我试图以某种方式调试为任何连接创建单独的接受器,io_service - 没有帮助。谁能指出我哪里出错?
P.S。 Visual Studio 2013
答案 0 :(得分:4)
基于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.
特别注意每个accept调用只接受一个连接,并且一次监听同一个端口时不应该有多个accept,所以你需要在上一次调用的处理程序中再次调用async_accept。 p>
Boost ASIO有一些非常好的教程示例,如this one