问题
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
回答1:
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.
回答2:
the server program looks like below.
recv(newsockfd,buf,20,0);
printf("Buffer is %s\n",buf);
This is already wrong. It should be:
int count = recv(newsockfd,buf,20,0);
if (count == -1)
{
perror("recv"); // please improve this message
close(newsocketfd);
}
else if (count == 0)
{
// peer has closed the connection
close(newsockfd);
}
else
{
printf("Buffer is %.*s\n",count,buf);
}
This should give you enough of a hint ...
回答3:
You've got 2 issues:
When you're displaying the results, you're going to stop at the first null byte, which is always after "Messgfromlient". There may be more text already received, but you're not displaying it.
The second issue is that the TCP connection is a stream. You may receive all the data in one go, you may receive only the first byte. You don't know which one is it and can't predict it. You need to handle incomplete reads in your application and you have to handle retries.
You can however make it more likely that all the data will be sent in one packet rather than 6. Have a look at the TCP_CORK option.
来源:https://stackoverflow.com/questions/37250887/sending-multiple-send-recv-in-socket