C connect实现Timeout效果(Windows)

int SocketClient::connectTimeOutForWin(SOCKET &connect_fd, const int &timeout, const sockaddr_in &server)
{
int error=-, len;
len = sizeof(int);
timeval tm;
fd_set set;
unsigned long ul = ; //设置为非阻塞模式 ioctlsocket(connect_fd,FIONBIO,&ul); bool ret = false;
if( connect(connect_fd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -)
{
tm.tv_sec = timeout;
tm.tv_usec = ;
FD_ZERO(&set);
FD_SET(connect_fd, &set);
if( select(-, NULL, &set, NULL, &tm) > )
{ getsockopt(connect_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len); if(error == ) ret = true;
else ret = false;
} else ret = false;
}
else ret = true;
ul = ; //设置为阻塞模式
ioctlsocket(connect_fd,FIONBIO,&ul); if(!ret){
closesocket(connect_fd);
// fprintf(stderr,"Connect server fail in WIN\n");
}
return ret;
}

windows网络编程之socket中的非阻塞connect()与getsockopt()

上一篇:【ASP.NET Core】从向 Web API 提交纯文本内容谈起


下一篇:37. Binary Tree Zigzag Level Order Traversal && Binary Tree Inorder Traversal