0

我为聊天室编写了这个模块,每当套接字死亡时,它都应该尝试重新连接。但是,我注意到大约 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);
}
4

1 回答 1

2

我看不到“如果套接字死了,请重新连接”的代码。我确实看到了“当我要求您连接时,请尝试循环连接直到成功”的代码。他们是两个不同的东西。您的代码中是否还有其他地方在循环中不断调用 start() ?start() 函数中的命令循环将在套接字错误时“中断”....并且我没有看到任何在中断后重新连接的尝试。

于 2013-05-27T06:54:52.043 回答