我有一个服务器,使用带有以下代码的asio,100%从示例中复制。当没有连接时,代码表现良好。但是,一旦第一个客户端连接,句柄接受开始输出大量系统: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;
}