![](/img/trans.png)
[英]How boost::asio::ip::tcp::acceptor work with TCP_DEFER_ACCEPT and TCP_FASTOPEN
[英]C++ boost::asio::ip::tcp::acceptor sometimes doesn't accept connector?
我目前有一個非常奇怪的問題。 有時我的::acceptor(使用 async_accept)不接受套接字(沒有調用 async_accept 中指定的接受函數)但連接器在連接函數(boost::asio::類)上返回 true 。 有時一切正常,但有時我沒有得到一個接受器套接字......我真的不知道為什么了。 我在 Win10 64bit 下使用不同的 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();
}
__接受():
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...
[...]
所以......不應該每次當連接器套接字成功連接接受器套接字時也被創建嗎? 我希望有人知道這里出了什么問題:/
好的,我找到了答案...... io_service::run 函數沒有按我預期的那樣工作。 我認為如果不調用 io_service::stop 它將永遠阻塞。 好像那是錯的。 因為我在一次 ::run 調用之后中斷了我的 while 循環,然后線程完成了 io_service 有時在連接器套接字連接時不再運行。 更改了 io_service::run -> run_one() 並刪除了中斷。 現在將添加一個循環取消變量,因此它不是無限循環......
感謝您的回答!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.