我为聊天室编写了这个模块,每当套接字死亡时,它都应该尝试重新连接。但是,我注意到大约 10 或 15 分钟后,套接字将停止尝试重新连接。为什么会发生这种情况?我的代码如下:
bool Socket::Connection::_connect(int delay_ms)
{
closesocket(sock);
hostEntry = gethostbyname(host);
if( !hostEntry )
{
//Couldn't resolve our host
return false;
}
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if( sock == INVALID_SOCKET )
{
//Invalid socket
return false;
}
SOCKADDR_IN serverInfo;
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr = *(LPIN_ADDR)*hostEntry->h_addr_list;
serverInfo.sin_port = htons(port);
int nret = SOCKET_ERROR;
while( (nret == SOCKET_ERROR) )
{
nret = connect(sock, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
if( nret == SOCKET_ERROR )
Sleep(delay_ms);
if( running == false )
return false;
}
return true;
}
void Socket::Connection::start()
{
u_long iMode = 1;
fd_set rdevents;
struct timeval tv;
while( 1 ) //Outer, connection loop
{
if( !_connect(RECONNECT_TIME) )
continue;
int nret = ioctlsocket(sock, FIONBIO, &iMode);
if( nret != NO_ERROR )
continue;
//if( onconnect != NULL )
//onconnect(sock);
while( 1 ) //Inner, command loop
{
FD_ZERO( &rdevents );
FD_SET( sock, &rdevents );
tv.tv_sec = 8;
tv.tv_usec = 0;
nret = select(0, &rdevents, NULL, NULL, &tv);
if( nret == SOCKET_ERROR )
{
break;
}
else if( nret > 0 )
{
if( FD_ISSET(sock, &rdevents) )
{
char buf[1024];
nret = recv(sock, buf, 1024, 0);
if( nret == 0 )
break;
if( onrecv != NULL ) onrecv(sock, buf, nret);
}
}
}
}
closesocket(sock);
}