您好,登錄后才能下訂單哦!
場景
boost庫中的asio模塊,在阻塞模式下,調用connect進行服務器的連接,如果服務器沒有打開,默認情況下需要20秒的超時連接,才會返回。目前嘗試設置套接字的連接超時時間,都不奏效。估計只能修改boost源碼中的超時時間
//設置成非阻塞,然后調用select等待超時,無效
int TestBoostAsioConnectTimeout()
{
boost::asio::io_service ios;
boost::asio::ip::tcp::socket sock(ios);
boost::system::error_code ec;
sock.open(boost::asio::ip::tcp::v4());
// 設為非阻塞
sock.io_control(boost::asio::ip::tcp::socket::non_blocking_io(true));
sock.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(sock.native(), &fdWrite);
timeval tv = { 5 }; // 5秒超時
if (select(0, NULL, &fdWrite, NULL, &tv) <= 0
|| !FD_ISSET(sock.native(), &fdWrite))
{
std::cout << "連接超時" << std::endl;
sock.close();
return 0;
}
// 設回阻塞
sock.io_control(boost::asio::ip::tcp::socket::non_blocking_io(false));
std::cout << "連接成功" << std::endl;
sock.close();
return 0;
}
//獲取原始的套接字,進行屬性的設置
int TestBoostAsioConnectOverTime()
{
boost::asio::io_service ios;
boost::asio::ip::tcp::socket sock(ios);
boost::system::error_code ec;
sock.open(boost::asio::ip::tcp::v4());
// 設為非阻塞
sock.io_control(boost::asio::ip::tcp::socket::non_blocking_io(true));
int timeout = 3000;
int nRet = setsockopt(sock.native(), SOL_SOCKET, SO_CONNECT_TIME, (const char*)&timeout, sizeof(timeout));
nRet = setsockopt(sock.native(), SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
sock.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(sock.native(), &fdWrite);
timeval tv;
tv.tv_sec = 1; // 5秒超時
tv.tv_usec = 0;
if (select(0, NULL, &fdWrite, NULL, &tv) <= 0
|| !FD_ISSET(sock.native(), &fdWrite))
{
std::cout << "超時/出錯啦" << std::endl;
sock.close();
return 0;
}
// 設回阻塞
sock.io_control(boost::asio::ip::tcp::socket::non_blocking_io(false));
std::cout << "連接成功" << std::endl;
sock.close();
return 0;
}
設置超時的代碼:
windows:
int nTvlen=1000; //1s
int retOpt=setsockopt(m_Socket,SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTvlen,sizeof(nTvlen));
linux:
struct timeval nTvlen={1,0}; //1S
int retOpt=setsockopt(m_Socket,SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTvlen,sizeof(nTvlen));
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。