CSDN上求助無果,只好用自創的非主流方法了。 asio自帶的例子裏是用deadline_timer的async_wait方法來實現超時的,這種方法須要單獨寫一個回調函數,不利於把鏈接和超時封裝到單個函數裏。傳統的Winsock編程能夠先把socket設爲非阻塞,而後connect,再用select來判斷超時,asio也能夠這樣作,惟一「非主流」的是asio裏沒有一個相似select的函數,因此得調用原始的Winsock API,也就犧牲了跨平臺:ios
- #include <iostream>
- #include <boost/asio.hpp>
-
- int main()
- {
- boost::asio::io_service ios;
- boost::asio::ip::tcp::socket s(ios);
- boost::system::error_code ec;
-
- s.open(boost::asio::ip::tcp::v4());
-
- s.io_control(boost::asio::ip::tcp::socket::non_blocking_io(true));
-
- s.connect(
- boost::asio::ip::tcp::endpoint(
- boost::asio::ip::address::from_string("192.168.1.1"), 80)
- , ec);
- fd_set fdWrite;
- FD_ZERO(&fdWrite);
- FD_SET(s.native(), &fdWrite);
- timeval tv = {5};
- if (select(0, NULL, &fdWrite, NULL, &tv) <= 0
- || !FD_ISSET(s.native(), &fdWrite))
- {
- std::cout << "超時/出錯啦" << std::endl;
- s.close();
- return 0;
- }
-
- s.io_control(boost::asio::ip::tcp::socket::non_blocking_io(false));
- std::cout << "鏈接成功" << std::endl;
- s.close();
-
- return 0;
- }
|