3,881
社区成员
发帖
与我相关
我的任务
分享
int
Http::nonb_connect(int sockfd, struct sockaddr* sa, int sec) {
int status;
int begin_time = time(NULL);
fd_set wset, xset; /* xset: exceptfds set */
struct timeval timeout;
u_long iMode = 1;
ioctlsocket(sockfd, FIONBIO, &iMode);
if (connect(sockfd, sa, sizeof(struct sockaddr)) == 0) { /* Connect successful immediately */
ioctlsocket(sockfd, FIONBIO, &iMode); /* restore */
return 0;
}
if (WSAGetLastError() != WSAEWOULDBLOCK) { /* WSAEWOULDBLOCK */
cout << "there is something wrong!" << endl;
return -1;
}
FD_ZERO(&wset);
FD_SET(sockfd, &wset);
xset = wset;
timeout.tv_sec = sec;
timeout.tv_usec = 0;
status = select(sockfd + 1, NULL, &wset, &xset, &timeout);
switch (status) {
case -1: // Select error, set the socket as default blocking
ioctlsocket(sockfd, FIONBIO, &iMode);
cout << "2.fcntl() in nonb_connect" << endl;
return -1;
case 0: //Connection timed out.
ioctlsocket(sockfd, FIONBIO, &iMode);
cout << "3.fcntl() in nonb_connect" << endl;
return -1;
default: // Connected successfully.
if (FD_ISSET(sockfd, &wset)) {
/* 这里,用connect(), WSAEISCONN做一次检查 */
if ( (connect(sockfd, sa, sizeof(struct sockaddr)) != 0) &&
(WSAGetLastError() == WSAEISCONN))
{
ioctlsocket(sockfd, FIONBIO, &iMode);
return 0;
}
}
/* TODO: 1. connect() / WSAEISCONN检查失败!!
2. FD_ISSET(sockfd, &xset) 异常发生
*/
ioctlsocket(sockfd, FIONBIO, &iMode);
cout << "4.fcntl() in nonb_connect" << endl;
return -1;
}
}