CSDN上求助无果,只好用自创的非主流方法了。 asio自带的例子里是用deadline_timer的async_wait方法来实现超时的,这种方法需要单独写一个回调函数,不利于把连接和超时封装到单个函数里。传统的Winsock编程可以先把socket设为非阻塞,然后connect,再用select来判断超时,asio也可以这样做,唯一“非主流”的是asio里没有一个类似select的函数,所以得调用原始的Winsock API,也就牺牲了跨平台:
- #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;
- }
|