Sockets – sending multiple send/recv in socket

csocketstcp

I need bit clarification on using multiple send/recv in socket programs.
My client program looks below(Using TCP SOCK_STREAM).

    send(sockfd,"Messgfromlient",15,0);
    send(sockfd,"cli1",5,0);
    send(sockfd,"cli2",5,0);
    send(sockfd,"cli3",5,0);
    send(sockfd,"cli4",5,0);
    send(sockfd,"cli5",5,0);

and the server program looks like below.

    recv(newsockfd,buf,20,0);
    printf("Buffer is %s\n",buf);

when i execute the above program, the output is as below:

Client Msg :Messgfromlient

I believe that the buf size is 20, so only one buffer is getting received.
Adding one more recv on server side.

    char buf[20],buf[20];
     ------skipped------
    recv(newsockfd,buf,20,0);
    recv(newsockfd,buf1,20,0);
    printf("Client Msg  :%s\n",buf);
    printf("Client Msg  :%s \n",buf1);

output:
1st trial:

    Client Msg  :Messgfromlient
    Client Msg  :cli2 

2nd trail:

   Client Msg  :Messgfromlient
   Client Msg  :cli1

As we can see that there is some contradiction in the ouputs,
From client side it looks all the msgs are getting sent, but in server, msg will be received based on buf size,here eventhough buf1 has size of 20, why 'cli3''cli4''cli4' msgs are not getting received on buf1?. Is there any specific limit is there? Please clarify on this.

Thanks in Advance,
Raja

Best Answer

TCP is a byte stream based protocol, it knows nothing about messages. You send 25 bytes in total, and each recv on the other side will read some of those bytes. You can get 20, you might get 1 and then 19 in the next read, you might get 5 then 4 then 11 then 5. The size parameter to recv is the maximum number to read.

You need to loop until you read the whole message yourself, and also understand you might receive more than one "send" in the same received message.

Related Topic