csocketsclient-serverserverrecv

How recv() function works when looping?


I read in MSDN about the send() and recv() function, and there is one thing that I'm not sure I understand.

If I send a buffer of size 256 for example, and receive first 5 bytes, so the next time I call the recv() function, it will point to the 6th byte and get the data from there?

for example :

char buff[256];
memcpy(buff,"hello world",12);
send(sockfd, buffer, 100) //sending 100 bytes

//server side:
char buff[256];
recv(sockfd, buff, 5) // now buffer contains : "Hello"?
recv(socfd, buff,5) // now I ovveride the data and the buffer contains "World"?

thanks!


Solution

  • The correct way to receive into a buffer in a loop from TCP in C is as follows:

    char buffer[8192]; // or whatever you like, but best to keep it large
    int count = 0; 
    int total = 0; // total bytes received
    
    while ((count = recv(socket, &buffer[total], sizeof (buffer) - total, 0)) > 0)
    {
        total += count;
        // At this point the buffer is valid from 0..total-1, if that's enough then process it and break, otherwise continue
    }
    if (count == -1)
    {
        perror("recv");
    }
    else if (count == 0)
    {
        // EOS on the socket: close it, exit the thread, etc.
    }