Home > Back-end >  recv() not waiting for data
recv() not waiting for data

Time:02-12

On the first iteration of a while(1) loop for communication in a socket, everything works fine - on the second iteration, even though the connection is still open and ongoing (the server's send() waits for the user to insert data, on this same socket), the recv() from the client fails to wait for data.

while(1)
                memset(buffer, 0, 300);
                int nRet = recv(sock, buffer, 299, 0);
                printf("Recv: %d\n", nRet);
                if(nRet < 0)
                    fprintf(stderr, "recv() failed.");
                else if(nRet == 0)
                    continue;
                else
                    fprintf(stdout, buffer);

This is the beginning of the loop, which is of concern. The output, on the second iteration, is an infinite printing of "Recv: 0". This to me seems illogical - recv() is supposed to wait until data is sent, and none is being sent by the server.

CodePudding user response:

From the man page on my Linux system,

When a stream socket peer has performed an orderly shutdown, the return value will be 0 (the traditional "end-of-file" return).

Datagram sockets in various domains (e.g., the UNIX and Internet domains) permit zero-length datagrams. When such a datagram is received, the return value is 0.

The value 0 may also be returned if the requested number of bytes to receive from a stream socket was 0.

So either the connection was closed, or you received an 0-byte datagram. The endless repetition suggests the former. Repeatedly trying to read from a closed connection won't magically reopen it.

What it isn't is an error.

These calls return the number of bytes received, or -1 if an error occurred. In the event of an error, errno is set to indicate the error.

A signal interruption results in error EINTR. If the socket was made non-blocking and nothing is available, that results in error EAGAIN or EWOULDBLOCK. You aren't experiencing either of these.

  • Related