Kai
Kai

Reputation: 993

Maximum data size that can be sent and received using sockets, at once?(TCP socket)

I am designing a game which has master and multiple players. They send and receive data using TCP sockets.

Players transfer character strings between themselves via TCP sockets.The programs are being executed in red hat linux 6 os .

The character string transferred between players is of the type

char chain[2*hops+10];

The player code on sender side is

len = send(to,chain,sizeof(chain),0);
if (len != sizeof(chain)) {
perror("send");
exit(1);}

The code where player receives the data is like this :

char chain[2*hops+10];
len = recv(current,chain,sizeof(chain),0);

The value of hops is same for both the players. For hops value till around 8000 it is working fine, but once the hops value crosses some point, the same program is not working. I believe data is not transferred in one go. Is there a maximum buffer size for send and recv buffer?

Note: The sockets between them are opened using this code:

s = socket(AF_INET, SOCK_STREAM, 0);

and then the usual connect and bind sockets on both sides.

Upvotes: 3

Views: 16055

Answers (1)

Michael F
Michael F

Reputation: 40869

TCP is a stream-oriented protocol (as implied by SOCK_STREAM). Data that an application sends or receives (in [maximum-sized] chunks) is not received or sent in same-sized chunks. Thus one should read from a socket until enough data to be processed have been received, then attempt to process said data, and repeat:

while (true) {
    unsigned char buffer [4096] = {};

    for (size_t nbuffer = 0; nbuffer < sizeof buffer
                           ; nbuffer = MAX(nbuffer, sizeof buffer)) { /* Watch out for buffer overflow */
        int len = recv (sockd, buffer, sizeof buffer, 0);

        /* FIXME: Error checking */

        nbuffer += len;
    }

    /* We have a whole chunk, process it: */
    ;
}

You can also handle partial sends on the other side as described here, much better than I ever would.

Upvotes: 5

Related Questions