Search code examples
csocketstcprecv

How to handle recv() with MSG_DONTWAIT flag for data larger than 64KB on TCP socket?


I want to use non-blocking API of recv but it doesn't work after 64KB data and give error: Resource temporarily unavailable. So I use if(error == EAGAIN) but it stuck on receive because no data is available.

while(true) {
        ret = recv(csd, buf, size, MSG_DONTWAIT);

        if(errno == EAGAIN) {
            continue;
        }

        if (ret < 0) {
            perror("Error in receive\n");
            close(csd);
            exit(EXIT_FAILURE);
        } else if (ret == 0) {
            fprintf(stderr, "client disconnected\n");
            close(csd);
        } else {
            return buf;
        }
    }

Solution

  • By default the socket uses a 64k buffer internally and then the kernel refuses to accept more data. So recv() can return at most 64kb of data without waiting.

    You could change the buffer size for the socket (man 7 socket, SO_RCVBUF) or use a loop around select and recv to read it in multiple goes into a larger buffer as it becomes available.