我有一个服务器,使用带有以下代码的 asio,100% 从示例中复制。当没有连接时,代码表现良好。但是,一旦第一个客户端连接,句柄接受就开始输出大量的 system:9 错误,我无法连接任何其他客户端。连接的单个客户端可以很好地执行异步读/写。我对自己做错了什么感到茫然。我已经在线程池中尝试了有和没有 io_service 的代码,结果相同。
Server::Server(io_service& io_service,
const std::string address,
const std::string port)
: io_service_(io_service),
//zmq_strand_(io_service),
acceptor_(io_service) {
ip::tcp::resolver resolver(io_service_);
ip::tcp::resolver::query query(address, port);
ip::tcp::endpoint endpoint = *resolver.resolve(query);
acceptor_.open(endpoint.protocol());
acceptor_.set_option(ip::tcp::acceptor::reuse_address(true));
acceptor_.bind(endpoint);
acceptor_.listen();
start_accept();
}
void Server::start_accept() {
auto session = std::shared_ptr<Session>(new Session(io_service_,session_manager_));
acceptor_.async_accept(session->socket()
,std::bind(&Server::handle_accept,this,session,std::placeholders::_1));
}
void Server::handle_accept(std::shared_ptr<Session> session, const system::error_code& error) {
if (!error) {
std::cout << "handle_accept" << std::endl;
session->start();
} else {
std::cout << error << std::endl;
}
start_accept();
}
小更新:我没有使用 http3 示例,而是使用了 Denis 提出的示例。它不那么令人费解,并使服务器行为正确。我还没有找到一个合理的解释来解释为什么前一段代码不起作用。这样做:
Server::Server(
io_service &service,
const uint8_t num_threads,
const std::string address,
const uint16_t port)
:
num_threads_(num_threads),
//zmq_strand_(io_service),
acceptor_(service,ip::tcp::endpoint(ip::tcp::v4(),port)) {
//io_service::work work(io_service_);
start_accept();
}
void Server::start_accept() {
auto session = std::shared_ptr<Session>(new Session(acceptor_.get_io_service(),session_manager_));
acceptor_.async_accept(session->socket()
,std::bind(&Server::handle_accept,this,session,std::placeholders::_1));
}
void Server::handle_accept(std::shared_ptr<Session> session, const system::error_code& error) {
if (!error) {
std::cout << "handle_accept" << std::endl;
session->start();
}
start_accept();
}
void Server::start() {
std::set<std::unique_ptr<std::thread>> threads;
for( unsigned int i = 0; i < num_threads_; ++i ) {
threads.insert(std::unique_ptr<std::thread>(new std::thread( [&]() {
acceptor_.get_io_service().run();
})
));
}
std::cout << threads.size() << " threads started" << std::endl;
for(auto &t:threads) {
t->join();
}
std::cout << threads.size() << " threads joined" << std::endl;
}