Reputation: 1307
I wrote this module for a chat room, and whenever the socket dies it should try to reconnect. However, I've noticed that after around 10 or 15 minutes, the socket will stop trying to reconnect. Why could this happen? My code is as follows:
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);
}
Upvotes: 0
Views: 153
Reputation: 1885
I fail to see the code where it says 'if socket dies, reconnect'. I do see the code that says 'when I ask you to connect, try connection in a loop till that succeeds'. They are two different things. Is there something else somewhere in your code that keeps calling start() in a loop? The command loop in the start() function would be 'breaking' out on socket errors .... and I do not see any attempt to reconnect after that break out.
Upvotes: 2