- 论坛徽章:
- 39
|
从Multiget摘点代码
连接超時
- //with timeout connect
- #ifdef WIN32
- int CMgSocket::tconnect(SOCKET sock, const struct sockaddr *addr, unsigned int len)
- #else
- int CMgSocket::tconnect(int sock, const struct sockaddr *addr, unsigned int len)
- #endif
- {
-
- int ret, val;
- struct timeval tv;
- fd_set sset;
- #ifdef WIN32
- int lon;
- u_long iMode=1;
- ioctlsocket(sock,FIONBIO,&iMode);
- #else
- int flags,old_flags;
- socklen_t lon;
- flags = old_flags = fcntl(sock, F_GETFL, 0);
- flags |=O_NONBLOCK;
- if (fcntl(sock, F_SETFL, flags) == -1) {
- return -1;
- }
- #endif
-
- ret= connect(sock, addr, len);
- if(ret < 0)
- {
- #ifdef WIN32
- if (WSAEWOULDBLOCK == WSAGetLastError())
- #else
- if (errno == EINPROGRESS)
- #endif
- {
- tv.tv_sec = m_nConnectTimeOut;
- tv.tv_usec = 0;
- FD_ZERO(&sset);
- FD_SET(sock, &sset);
- if(select(sock+1, NULL, &sset, NULL, &tv) > 0)
- {
- lon = sizeof(int);
- #ifdef WIN32
- getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)(&val), &lon);
- #else
- getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)(&val), &lon);
- #endif
- if(val != 0)
- {
- ret= -1;
- }
- else
- {
- ret=0;
- }
- }
- else
- {
- ret= -1;
- }
- }
- else
- {
- ret = -1;
- }
- }
- #ifdef WIN32
- iMode=0;
- ioctlsocket(sock,FIONBIO,&iMode);
- #else
- fcntl(sock, F_SETFL, old_flags);
- #endif
- return ret;
- }
复制代码 |
|