我正在使用pion网络库,使用其同步API,通过同步我的意思是在阻止模式下连接到服务器。 问题是连接可能很长,所以我需要设置超时。
我搜索了很多东西并找到了一些东西:首先将套接字设置为非阻塞,然后连接,这是我的代码:
int main() {
string ip = "65.233.167.165"; // some fake ip maybe not even exists
int port = 80;
boost::asio::io_service io_service;
boost::asio::ip::address addr;
addr = addr.from_string(ip);
boost::asio::ip::tcp::endpoint endpoint(addr, port);
// socket
boost::asio::ip::tcp::socket s(io_service);
s.open(boost::asio::ip::tcp::v4());
// set to non-blocking
s.io_control(boost::asio::ip::tcp::socket::non_blocking_io(true));
fd_set fdWrite;
FD_ZERO(&fdWrite);
FD_SET(s.native(), &fdWrite);
timeval tv = {3}; // timeout after 3 seconds
if (select(0, NULL, &fdWrite, NULL, &tv) <= 0
|| !FD_ISSET(s.native(), &fdWrite))
{
std::cout << "TIMEOUT" << std::endl;
s.close();
return 0;
}
// set back to blocking
s.io_control(boost::asio::ip::tcp::socket::non_blocking_io(false));
// connect
boost::system::error_code ec;
s.connect(endpoint, ec);
if(ec) {
std::cout << "error: " << ec.message() << endl;
}
}
它有效,所以我尝试用pion这个技巧。首先,将行65.233.167.165 www.mytest.org
添加到etc / hosts以将域绑定到测试ip。然后是代码:
string host = "www.mytest.org";
int port = 80;
using namespace boost;
using boost::asio::ip::tcp;
pion::tcp::connection con(io_service, false);
con.get_socket().open(boost::asio::ip::tcp::v4());
// set to non-blocking
con.get_socket().io_control(boost::asio::ip::tcp::socket::non_blocking_io(true));
cout << "now connect" << endl;
con.connect(host, port);
fd_set fdWrite;
FD_ZERO(&fdWrite);
FD_SET(con.get_socket().native(), &fdWrite);
timeval tv = {3}; // 3 seconds timeout
if (select(0, NULL, &fdWrite, NULL, &tv) <= 0
|| !FD_ISSET(con.get_socket().native(), &fdWrite))
{
cout << "connect timeout" << endl;
return 1;
}
cout << "connected or timeout" << endl;
// set back to blocking
con.get_socket().io_control(boost::asio::ip::tcp::socket::non_blocking_io(false));
超时不起作用。
有什么想法吗?感谢。