我为聊天室写了这个模块,每当套接字死掉,它应该尝试重新连接。但是,我注意到在大约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);
}
答案 0 :(得分:2)
我没有看到代码所说的“如果套接字死了,重新连接”。我确实看到代码中写着“当我要求你连接时,尝试连接循环直到成功”。他们是两个不同的东西。你的代码中是否还有其他东西在循环中调用start()? start()函数中的命令循环将“破坏”套接字错误....并且我没有看到任何尝试在该分解后重新连接。