gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:49:31 26 4
gpt4 key购买 nike

我正在编写简单的同步 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()”字符串上正确触发断点。但是,如果我想创建第二个连接(第一个连接是否断开并不重要)-> telnet 已连接,但未触发下一个“接受”字符串上的断点,并且连接未响应任何内容。

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

附言 Visual Studio 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.

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

Boost ASIO 有一些很好的教程示例,例如 this one

关于c++ - boost::asio 同步服务器在第一个之后不接受连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com