How to add server connection timeout using select()?

Issue

This Content is from Stack Overflow. Question asked by XoDefender

I want to add a timeout to connect to a server because if the server is switched off my application stops working and starts waiting for the server reply for 1 minute. I want to stop trying to connect to the server after a fixed amount of time. They say that I should use select(), but I do not understand how to integrate it in a code below:

    int client;
    bool isExit = false;
    int fileSize = 0;
    int size = 0;
    int bufsize = 1024;
    char buffer[bufsize];

    string fileEnd = "<EOF>";

    string modelFolder = currentModelFolder;

    replace(modelFolder.begin(),
            modelFolder.end(),
            ';',
            '/');

    string requestStructure = modelFolder + "/" + currentFileName + "/" + fileEnd + "|" + '';

    char *bytes = new char[requestStructure.length()];
    memcpy(bytes, requestStructure.data(), requestStructure.length());

    sockaddr_in server_addr;

    client = socket(AF_INET, SOCK_STREAM, 0);

    if (client < 0)
    {
        cout << "Error establishing socket..." << endl;
        exit(1);
    }
    else
        cout << "Socket client has been created..." << endl;

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(serverPort);
    inet_aton(serverIp.c_str(), &server_addr.sin_addr);

    if (connect(client, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 0)
    {
        cout << "=> Connection to the server port number: " << serverPort << endl;
    }

    // отправка запроса на сервер (сервер, данные, размер пакета)
    send(client, bytes, bufsize, 0);
    cout << "=> Awaiting confirmation from the server..." << endl;

    // получение данных с сервера (сервер, массив байтов, размер пакета)
    recv(client, buffer, bufsize, 0);
    cout << "Buffer = " << buffer << endl;

    int bufferStringSize = sizeof(buffer);
    string bufferSize = convertToString(buffer, bufferStringSize);

    stringstream stringToIntStream;
    stringToIntStream << bufferSize;
    stringToIntStream >> fileSize;

    ostringstream stepFilePathStructure;
    stepFilePathStructure << saveFolderPath << currentFileName << "";

    string stepFilePath = stepFilePathStructure.str();

    remove(stepFilePath.c_str());

    ofstream stepFile;
    stepFile.open(stepFilePath);

    while (size < fileSize)
    {
        int received = recv(client, buffer, bufsize, 0);

        stepFile.write(buffer, received);

        size += received;
    }

    close(client);



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?