我现在有个很奇怪的问题。有时my ::acceptor (使用async_accept)不接受套接字(没有调用async_accept中指定的accept函数),但是连接器在connect函数上返回true (两者都是boost::asio::classes)。有时一切正常,但有时我没有接受者插座.我真的不知道为什么了。我在Win10 64位下用不同的listen_ports测试了所有东西。
我的服务器结构如下:
io_service:
_io_thread = std::make_unique<std::thread>([this]() {
while (1)
{
try
{
_io_service->run();
break;
}
catch (const boost::exception& e)
{
spdlog::error("IO_SERVICE_EXCEPTION: ", boost::diagnostic_information(e));
}
}
});受体:
void Server::initialize(uint16_t listen_port)
{
// at this point the io_thread is running already
auto endpoint = ip::tcp::endpoint(ip::tcp::v4(), listen_port);
_acceptor = std::make_unique<boost::asio::ip::tcp::acceptor>(*_io_service, endpoint.protocol());
_acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(false));
_acceptor->bind(endpoint);
_acceptor->listen();
_listen_port = listen_port;
__accept();
}__accept():
void Server::__accept()
{
// create socket for next connection
_acceptor_socket = std::make_unique<ip::tcp::socket>(*_io_service);
_acceptor->async_accept(*_acceptor_socket, [this](const boost::system::error_code& err)
{
spdlog::info("Accept new socket..."); // this sometimes doesn't get called :(
if (err.failed())
{
// acceptor closed
if (err == boost::asio::error::operation_aborted)
{
spdlog::info("network server stopped accepting sockets");
return;
}
// unknown error
spdlog::error("network server accepting socket failed {} message {} num {}", err.failed(), err.message(), err.value());
// accept next connection
__accept();
return;
}
// accept new socket
_new_connections_mutex.lock();
auto con = __create_new_connection();
con->initialize(++_connection_id_counter, std::move(_acceptor_socket));
con->set_handler(_input_handler);
con->goto_phase(_initial_phase);
spdlog::info("new connection from {} with id {}", con->get_host_name(), con->get_unique_id());
_new_connections[con->get_unique_id()] = std::move(con);
_new_connections_mutex.unlock();
// wait for next connection
__accept();
}
);
}我的客户机连接器很简单,如下所示:
auto socket = std::make_unique<boost::asio::ip::tcp::socket>(*_io_service);
spdlog::info("try to connect to {}:{}", endpoint.address().to_string(), endpoint.port());
try
{
socket->connect(endpoint);
}
catch (const boost::system::system_error & e)
{
spdlog::error("cannot connect to {}:{}", endpoint.address().to_string(), endpoint.port());
return false;
}
// this succeeds everytime...
[...]所以..。当连接器套接字成功连接受主套接字时,不应该每次都创建吗?我希望有人知道这里出了什么问题
发布于 2020-02-06 18:44:34
好吧我找到答案了..。io_service::run函数不像我预期的那样工作。我以为如果不调用io_service::stop,它就会永远阻塞。看来这是不对的。因为我中断了一个::运行调用出我的when循环,然后线程完成,当连接器套接字连接时,io_service有时不再运行。已经更改了io_service::run -> run_one()并删除了中断。现在将添加一个循环-取消变量,因此它不是无限循环.
谢谢你的回答!
https://stackoverflow.com/questions/60096599
复制相似问题