bemeyer
bemeyer

Reputation: 6231

TCP connecting to server is slow?

I am running a TCP Server which accepts java clients fast. But the c++ Client does need like ~1Second to connect to it. (used a scopetime logger) What i do is, i connect to the server befor sending and the communication is done i do close the socket and the next time i do send something i do the same procedure.

the for loop to connect to the socket really really slow. How do i improve this?! (the connect is slow)

is it the Client or meight it be the server here? If it could be the server i wonder why it isnt slow if a java client connects

bool JIMDBClient::connect()
{
    WSADATA wsaData;
    m_sock = INVALID_SOCKET;
    struct addrinfo* result = nullptr, *ptr = nullptr, hints;

    int iResult;

    /* Initialisiere TCP für Windows ("winsock"). */
    WORD wVersionRequested;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0)
    {
        printf("WSAStartup failed with error: %d\n", iResult);
        m_connected = false;
        return false;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(m_host.c_str(), m_port.c_str(), &hints, &result);
    if (iResult != 0)
    {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        m_connected = false;
        return false;
    }

    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) // this is slow
    {
        // Create a SOCKET for connecting to server
        m_sock = socket(ptr->ai_family, ptr->ai_socktype,
                        ptr->ai_protocol);
        if (m_sock == INVALID_SOCKET)
        {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            m_connected = false;
            return false;
        }

        // Connect to server.
        iResult = ::connect(m_sock, ptr->ai_addr, static_cast<int>(ptr->ai_addrlen));
        if (iResult == SOCKET_ERROR)
        {
            closesocket(m_sock);
            m_sock = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (m_sock == INVALID_SOCKET)
    {
        WSACleanup();
        m_connected = false;
        return false;
    }

    if(!handShake()) //only takes around 450µS !
    {
        LOG_WARN << "handshake failed";
        WSACleanup();
        m_connected = false;
        return false;
    }

    m_connected = true;
    return m_connected;
}

Upvotes: 1

Views: 1147

Answers (1)

Alan Stokes
Alan Stokes

Reputation: 18964

If you know that your server only supports IPv4 or IPv6 you can say that in the hints that you pass to getaddrinfo:

hints.ai_family = AF_INET; // Or AF_INET6

Upvotes: 2

Related Questions