采用tcp协议,如果连接一个无效的ip地址, 将会有20s左右的阻塞时间。这是由于采用Nagel算法和blocking模式导致的,解决办法:
static int TryConnect( SOCKET s, const struct sockaddr FAR *name, int namelen, int timeout )
{
fd_set fsWrite;
struct timeval tvTimeout;
ULONG uNonBlocked=1;
tvTimeout.tv_sec = 0;
tvTimeout.tv_usec = timeout*1000;
/* 设置为非阻塞模式进行连接 */
uNonBlocked = 1;
if( ioctlsocket(s, FIONBIO, (ULONG *)&uNonBlocked) == SOCKET_ERROR )
return -1;
if( connect(s, name, namelen) == SOCKET_ERROR)
{
if( WSAGetLastError() == WSAEWOULDBLOCK )
{
FD_ZERO(&fsWrite);
FD_SET(s, &fsWrite);
if( select(s+1, NULL, &fsWrite, NULL, &tvTimeout) < 0 )
{
return -1;
}
if( !FD_ISSET(s, &fsWrite) )
{
return -1;
}
/* 设置为阻塞模式进行通讯 */
uNonBlocked = 0;
if( ioctlsocket(s, FIONBIO, (ULONG *)&uNonBlocked) == SOCKET_ERROR )
{
DPRINT("dd/n");
return -1;
}
}
else
return -1;
}
uNonBlocked = 0;
if( ioctlsocket(s, FIONBIO, &uNonBlocked) == SOCKET_ERROR )
return -1;
return 0;
}