我正在建立一个P2P文件共享程序,我可以在连接到我的Wifi路由器的计算机之间传输文件。 但是,当我在具有localhost地址的计算机上运行它时,程序的发送方部分成功地将所有数据发送到接收方程序,但是我的接收方没有获得所有数据。我在机器上的单独端口上运行这两个。当我在单独的机器上运行发送器和接收器时,不会发生此问题。
这是我的接收代码段
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()无法处理数据并因此错过了一些数据?
谢谢
答案 0 :(得分:1)
假设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);
}