Установить тайм-аут для boost socket.connect

я использую boost::asio::connect на tcp::socket, Когда все идет хорошо, connect немедленно возвращается, но в плохой сети, connect время ожидания после ожидания журнала 15 секунд. Я не могу позволить себе ждать так долго и поэтому хочу сократить время ожидания. К сожалению, я не нашел ни одного решения.

Я вижу решения, в которых async_wait используется вместе с deadline_timer, но все эти примеры предназначены для операций приема / отправки, а не для соединения.

Может ли кто-нибудь помочь мне с примером кода для boost::asio::connect(socket, endpoints);, Требование заключается в том, что время ожидания должно составлять 5 секунд вместо 15.

1

Решение

Вы взглянули на следующий пример? он содержит пример кода async_connect с тайм-аутом.

http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/example/timeouts/blocking_tcp_client.cpp

Метод connect with timeout может быть реализован с использованием следующего кода:

void connect(const std::string& host, const std::string& service,
boost::posix_time::time_duration timeout)  {
// Resolve the host name and service to a list of endpoints.
tcp::resolver::query query(host, service);
tcp::resolver::iterator iter = tcp::resolver(io_service_).resolve(query);

// Set a deadline for the asynchronous operation. As a host name may
// resolve to multiple endpoints, this function uses the composed operation
// async_connect. The deadline applies to the entire operation, rather than
// individual connection attempts.
deadline_.expires_from_now(timeout);

// Set up the variable that receives the result of the asynchronous
// operation. The error code is set to would_block to signal that the
// operation is incomplete. Asio guarantees that its asynchronous
// operations will never fail with would_block, so any other value in
// ec indicates completion.
boost::system::error_code ec = boost::asio::error::would_block;

// Start the asynchronous operation itself. The boost::lambda function
// object is used as a callback and will update the ec variable when the
// operation completes. The blocking_udp_client.cpp example shows how you
// can use boost::bind rather than boost::lambda.
boost::asio::async_connect(socket_, iter, var(ec) = _1);

// Block until the asynchronous operation has completed.
do io_service_.run_one(); while (ec == boost::asio::error::would_block);

// Determine whether a connection was successfully established. The
// deadline actor may have had a chance to run and close our socket, even
// though the connect operation notionally succeeded. Therefore we must
// check whether the socket is still open before deciding if we succeeded
// or failed.
if (ec || !socket_.is_open())
throw boost::system::system_error(
ec ? ec : boost::asio::error::operation_aborted);
}
3

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector