2

我是有关套接字编程的初学者,当我使用不同的缓冲区大小为发送者和接收者通过套接字发送数据时遇到问题。我必须制作2个基本程序,说话者和听众。必须将所有传入标准输入的内容发送出去,通过套接字发送,接收方必须打印数据。问题是当我为发送方和接收方使用不同的缓冲区大小时,接收方打印的数据不完整或乱序。我不明白为什么?

以下是最相关的一段代码:

听众:

#define BUFFERSIZE 20

...

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

说话者:

#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");
}

例如,使用此测试文件:

abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

它会打印

➜  ./listener                                        
abcdefghijklmnopqrabcdefghiiz
recv: Success
abcdefghijklmnopqrr    

我做错了什么?

谢谢你的工作!

4

1 回答 1

2

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) {
...
于 2012-04-08T12:00:33.933 回答