本地主机上的 recv() 数据丢失

recv() data loss on localhost

我正在构建一个 P2P 文件共享程序,我可以在连接到我的 Wifi 路由器的计算机之间传输文件。 但是,当我 运行 它在我的计算机上使用本地主机地址时,我程序的发送方部分成功地将所有数据发送到接收方程序,但我的接收方没有获得所有数据。我 运行 在我的机器上将这两个端口连接到不同的端口。当我 运行 发送者和接收者在不同的机器上时,问题不会发生。

这是我的接收代码片段

    while ((len = recv(welcomeSocket, buffer, BUFSIZ, 0)) > 0 && remain_data > 0)
    {
            fwrite(buffer, sizeof(char), len, received_file);
            remain_data -= len;
            fprintf(stdout, "Receive %zd bytes and we hope :- %d bytes\n", len, remain_data);

    }

这是我的发送代码片段

     while (((sent_bytes = sendfile(fds[i].fd, fd, offset, BUFSIZ)) > 0) && (remain_data > 0))
    {
            fprintf(stdout, "Server sent %u bytes from file's data, offset is now : %jd \n", sent_bytes, (intmax_t)offset);
            remain_data -= sent_bytes;
            fprintf(stdout, "remaining data = %d\n", remain_data);
    }

发送端的输出是

Server sent 8192 bytes from file's data, offset is now : 0 
remaining data = 30292
Server sent 8192 bytes from file's data, offset is now : 0 
remaining data = 22100
Server sent 8192 bytes from file's data, offset is now : 0 
remaining data = 13908
Server sent 8192 bytes from file's data, offset is now : 0 
remaining data = 5716
Server sent 5716 bytes from file's data, offset is now : 0 
remaining data = 0

接收方的输出是

Receive 256 bytes and we hope :- 38228 bytes
Receive 8192 bytes and we hope :- 30036 bytes
Receive 8192 bytes and we hope :- 21844 bytes
Receive 8192 bytes and we hope :- 13652 bytes
Receive 5716 bytes and we hope :- 7936 bytes

再一次,当 运行在不同的机器上运行这些程序并且 recv() 获取所有数据时,这不会发生。 localhost 的通信路径是否如此之快以至于 recv() 无法处理数据并因此遗漏了一些数据?

谢谢

假设 remain_data 是实际的文件大小,那么你的两个循环都是错误的。他们应该更像这样:

while (remain_data > 0)
{
    len = recv(welcomeSocket, buffer, min(remain_data, BUFSIZ), 0);
    if (len <= 0) {
        // error handling...
        break;
    }
    fwrite(buffer, sizeof(char), len, received_file);
    remain_data -= len;
    fprintf(stdout, "Receive %zd bytes and we hope :- %d bytes\n", len, remain_data);
}

off_t offset = 0;
while (remain_data > 0)
{
    sent_bytes = sendfile(fds[i].fd, fd, &offset, min(remain_data, BUFSIZ));
    if (sent_bytes <= 0) {
        // error handling...
        break;
    }
    fprintf(stdout, "Server sent %u bytes from file's data, offset is now : %jd \n", sent_bytes, (intmax_t)offset);
    remain_data -= sent_bytes;
    fprintf(stdout, "remaining data = %d\n", remain_data);
}