0

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 + "|" + '\0';

    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);
XoDefender
  • 33
  • 6
  • have a look at this: https://stackoverflow.com/questions/2597608/c-socket-connection-timeout – ruff09 Sep 19 '22 at 07:22

0 Answers0