处理多个站点连接的有效方法?

时间:2019-07-11 10:52:51

标签: c++ sockets

我编写了一个应用程序,该程序将一些文件发送到多个站点。如果某些站点没有启动,那么我应该如何处理连接。我应该只是放弃站点(比较容易的站点),还是尝试在特定时间段后并以固定的次数连接到那些站点(我觉得是正确的站点)。

我已经编写了支持发送和接收文件的应用程序。在下面的代码中

    //I have added one more loop to process all the configured sites.
    int socketHandle = 0;
    struct addrinfo ipList, *listHead = nullptr, *listElement = nullptr;

    cout << "Trying to connect to " << serverName << " on port " << serverPort << endl;

    memset(&ipList, '\0', sizeof(struct addrinfo));

    ipList.ai_family = AF_UNSPEC;
    ipList.ai_socktype = SOCK_STREAM;
    ipList.ai_protocol = IPPROTO_TCP;

    if((socketHandle = getaddrinfo(serverName, serverPort, &ipList, &listElement)) != 0)
    {
        cout << "getaddrinfo error for " << serverName << " " << serverPort << " " << gai_strerror(socketHandle) << endl;
    }

    listHead = listElement;

    bool bConnected = false;
    int nLastError = 0;
    do{

        m_nSocketHandle = socket(listElement->ai_family, listElement->ai_socktype, listElement->ai_protocol);
        if(m_nSocketHandle == 0)
        {
            continue;
        }

        nLastError = connect(m_nSocketHandle, listElement->ai_addr, listElement->ai_addrlen);
        if(nLastError == 0)
        {
            bConnected = true;
            break;
        }

        nLastError = GetLastError();

        close(m_nSocketHandle);
        m_nSocketHandle = 0;

    }while ((listElement = listElement->ai_next) != NULL);

    freeaddrinfo(listHead);/*It loops over and frees the whole list*/

我的问题只是从设计的角度来看。如果有人可以提出自己的想法并提出自己的理解,将不胜感激。这是我的第一个问题。

0 个答案:

没有答案