user2552904
user2552904

Reputation: 21

Nonblocking sockets even if not explicitly setting them as nonblocking

I have a TCP application written in C++, where a client and a server exchange data. I've istantiated a socket, believing that it would have been blocking by default; on the contrary, after server waits for a client, I have that client calls the recv function without waiting for data. This is the code in which I inizialize the socket fr the client.

int TCPreceiver::initialize(char* address, int port)
{
    sock = socket (AF_INET, SOCK_STREAM, 0);
    cout << "Socket: " << sock << endl;
    sockaddr_in target;
    target.sin_family = AF_INET;
    target.sin_port = htons (port);
    target.sin_addr.s_addr = inet_addr(address);

    int fails=0;
    while (connect(sock, (sockaddr*) &target, sizeof(target)) == -1)
    {
        fails++;
        if (fails==10)
        {
            close(sock);
            cout << "Error with connection to the server, try again"<< endl;
            exit(-1);
        }
    }

    cout << "Client connected (control channel)" << endl;

    unsigned char text[10]; //Request message
    //fill text[]
    if(send(sock, (char*)text, 10, 0)==-1)
    {
            printf("send() failed with error code : %d" , -1);
            exit(EXIT_FAILURE);
    }

    return 0;
}

I've tried adding this code:

int opts;
opts = fcntl(sock,F_GETFL);
if (opts < 0) {
    perror("fcntl(F_GETFL)");
    exit(0);
}
opts = (opts & (~O_NONBLOCK));
if (fcntl(sock,F_SETFL,opts) < 0) {
    perror("fcntl(F_SETFL)");
    exit(0);
}

but it still doesn't work, and if I call the recv(), the application doesn't block (and recv() always returns 0). Here is the function where I call the recv():

void TCPreceiver::receive(char* text, int& dim)
{
    int ret;

    ret = recv(sock, text, dim, 0);
    dim=ret;
    if(ret == -1){
        printf("recv() failed with error (%d)\n", ret);
        //system("PAUSE");
        exit(1);
    }
}

Where am I wrong?

Upvotes: 0

Views: 85

Answers (1)

user207421
user207421

Reputation: 310884

recv() returning zero indicates either (1) you passed a zero length, which is just a programming error which I won't discuss further here, or (2) end of stream. The peer has close the connection. This isn't a non-blocking situation, this is the end of the connection. You must close the socket and stop using it. It will never return anything. It zero ever again.

See the man pages.

Upvotes: 3

Related Questions