您的位置:首页 > 理论基础 > 计算机网络

Winsock TCP连接失败时长时间挂起的解决办法

2008-02-27 21:48 239 查看
采用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐