c++ - Set timeout for boost socket.connect -
i using boost::asio::connect
on tcp::socket
. when goes fine, connect
returns on poor network, connect
times out after log wait of 15 seconds. cannot afford wait long , want reduce timeout. unfortunately have not come across solution far.
i see solutions async_wait been used deadline_timer examples receive / send operations , not connect.
can me sample code boost::asio::connect(socket, endpoints);
. requirement should timeout in 5 seconds instead of 15.
have take following example? contains sample code async_connect timeout.
http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/example/timeouts/blocking_tcp_client.cpp
the connect timeout method implemented using following code:
void connect(const std::string& host, const std::string& service, boost::posix_time::time_duration timeout) { // resolve host name , service list of endpoints. tcp::resolver::query query(host, service); tcp::resolver::iterator iter = tcp::resolver(io_service_).resolve(query); // set deadline asynchronous operation. host name may // resolve multiple endpoints, function uses composed operation // async_connect. deadline applies entire operation, rather // individual connection attempts. deadline_.expires_from_now(timeout); // set variable receives result of asynchronous // operation. error code set would_block signal // operation incomplete. asio guarantees asynchronous // operations never fail would_block, other value in // ec indicates completion. boost::system::error_code ec = boost::asio::error::would_block; // start asynchronous operation itself. boost::lambda function // object used callback , update ec variable when // operation completes. blocking_udp_client.cpp example shows how // can use boost::bind rather boost::lambda. boost::asio::async_connect(socket_, iter, var(ec) = _1); // block until asynchronous operation has completed. io_service_.run_one(); while (ec == boost::asio::error::would_block); // determine whether connection established. // deadline actor may have had chance run , close our socket, // though connect operation notionally succeeded. therefore must // check whether socket still open before deciding if succeeded // or failed. if (ec || !socket_.is_open()) throw boost::system::system_error( ec ? ec : boost::asio::error::operation_aborted); }
Comments
Post a Comment