-1

I am making a small program that has a server and client communicating on the same machine, which is does. But I can't get the server to wait to receive a message back from the client. Why does the loop not wait at the int iRecvA = recv(acceptSocket, machId, STRLEN, 0); line like it does the first time around? I proceeds to the last else.

while (!done)
{
    int iRecvA = recv(acceptSocket, machId, STRLEN, 0);
    int iRecvB = recv(acceptSocket, serialNum, STRLEN, 0);

    if (iRecvA && iRecvB > 0)
    {
        //stuff
    }
    else if (iRecvA && iRecvB == 0)
    {
        cout << "Connection closed\n";
        cleanup(acceptSocket);
        return 0;
    }
    else
    {
        cerr << "ERROR: Failed to receive message\n";
        cleanup(acceptSocket);
        return 1;
    }


    strcpy_s(sendMessage, "Activation was successful!\n\n\n");
    int iSend = send(acceptSocket, sendMessage, strlen(sendMessage), 0);
    if (iSend == SOCKET_ERROR)
    {
        cerr << "ERROR: Failed to send message\n";
        cleanup(acceptSocket);
        return 1;
    }
}
Qwertie
  • 5,784
  • 12
  • 45
  • 89
trama
  • 1,271
  • 3
  • 14
  • 24
  • When you get an error from a system call such as recv() you must print it, not just some message of your own devising. Otherwise debugging becomes a mere guessing game. – user207421 Feb 09 '14 at 23:20

1 Answers1

-1

You have encountered end of stream on one of your sockets, but your code doesn't check for it properly. Your code doesn't check any of the return values properly. You seem to think that

iRecvA && iRecvB > 0

is true if they are both positive, and that

iRecvA && iRecvB == 0

is true if they are both zero. They're not. You need to check them separately, and also print the actual error. You should really check the result of the first recv() before you even attempt the second recv(), but to use your existing code structure:

if (iRecvA < 0 || iRecvB < 0)
{
    cerr << "ERROR: " << strerr[errno] << "Failed to receive message\n";
    close(iRecvA);
    close(iRecvB);
    cleanup(acceptSocket);
    return 1;
}
// else
if (iRecvA == 0 || iRecvB == 0)
{
    cout << "Connection closed\n";
    close(iRecvA);
    close(iRecvB);
    cleanup(acceptSocket);
    return 0;
}
// else
{
    // stuff
}

Note also that else after return is redundant.

user207421
  • 305,947
  • 44
  • 307
  • 483