Patrick Browne
Patrick Browne

Reputation: 5480

trouble when send and recv buffer size are different

I'm a beginner concerning socket programming and I have a problem when I send data over the socket using a different buffer size for the sender and for the receiver. I have to make 2 basic program, talker and listener. One has to send everything passed into stdin, send it over the socket and the receiver must print the data. The problem is that when I use different buffer size for the sender and the receiver, the data that is printed by the receiver is incomplete or out of order. I don't understand why ?

Here are the most relevant piece of code :

Listener :

#define BUFFERSIZE 20

...

while((numbytes = recv(new_fd, buf, BUFFERSIZE - 1, 0)) > 0) {
    buf[numbytes] = 0;
    printf("%s", buf);
}
perror("recv");

Talker :

#define BUFFERSIZE 10

...

while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
{
    printf("%s", buffer);
    if ((numbytes = send(sockfd, buffer, sizeof buffer, 0)) == -1) {
        perror("talker: sendto");
        exit(1);
    }
    printf("\n");
}

For example, with this test file :

abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

it would print

➜  ./listener                                        
abcdefghijklmnopqrabcdefghiiz
recv: Success
abcdefghijklmnopqrr    

What is it that I'm doing wrong ?

Thanks for your work !

Upvotes: 2

Views: 1734

Answers (1)

diewie
diewie

Reputation: 764

Since you are only transmitting strings, you should not always send the complete buffer, but only the "length of the string", i.e. use strlen(buffer) instead of sizeof buffer. Then the strange behavior should be gone.

if ((numbytes = send(sockfd, buffer, strlen(buffer), 0)) == -1) {
...

Upvotes: 2

Related Questions