尝试以块的形式读取文件,并通过TCP连接发送每个块。当读/发循环完成时,我发送一条确认消息。每当我的文件大于一个块时(几乎总是如此),确认消息永远不会到达。无法判断这是因为它没有被发送或者没有收到。它似乎已发送但我无法确定。对于小文件,这很好用。在所有情况下都会正确发送文件本身,但我也需要发送此确认消息。
有人能看出为什么会发生这种情况吗?
int header_size = sizeof("file,,") + sizeof(int);
int bytes_remaining, filesize;
fseek(fp1, 0L, SEEK_END);
filesize = bytes_remaining = ftell(fd);
fseek(fd, 0L, SEEK_SET);
int bytes_to_read;
if ( (BUFFSIZE - header_size ) < bytes_remaining) {
bytes_to_read = BUFFSIZE - header_size;
} else {
bytes_to_read = bytes_remaining;
}
while (bytes_read = fread(buffer, 1, bytes_to_read, fd) > 0) {
sprintf(message, "file,%d,%s", bytes_to_read, buffer);
send(sd, message, bytes_to_read + header_size, 0);
bytes_remaining -= bytes_to_read;
if ( (BUFFSIZE - header_size) < bytes_remaining) {
bytes_to_read = BUFFSIZE - header_size;
} else {
bytes_to_read = bytes_remaining;
}
bzero(buffer, BUFFSIZE);
}
// send confirmation message
bzero(buf, 256);
sprintf(buf, "send_complete");
send(sd, buf, 256, 0);
fprintf(stdout, "complete: %s\n", buf);
答案 0 :(得分:2)
send()
,就像write()
或fwrite
不能保证所有数据都被消费一样。
您必须检查send()
的返回值,了解实际发送的字节数。
我猜你错过了确认消息,因为此时TCP输出缓冲区已满。