我正在尝试使用send() 和recv() 通过套接字TCP 发送。为了进行测试,我发送了一个 38 字节的较小文本文件。我使用此接收文件:
char * b = (char *)malloc(chunk + 2);
while (size > 0) {
memset(b, 0, chunk);
if (chunk > size) {
chunk = size;
}
if (size == total_size) {
gettimeofday(&tvB, NULL);
}
bytes_read = recv(ptr->sock, b, chunk, MSG_WAITALL);
if (bytes_read < 0) {
printf("ERROR: READ\n\n");
break;
}
if (bytes_read == 0) break;
int err = fwrite(b, sizeof(char), bytes_read, fp);
if (err <= 0) {
printf("ERROR: FWRITE\n\n");
break;
}
size -= bytes_read;
printf("SIZE: %d bytes_read = %d CHUNK: %d\n\n", size, bytes_read, chunk);
printf("TotalSize - size %d\n\n", total_size - size);
}
fclose(fp);
gettimeofday(&tvA, NULL);
我的发送方:
char * c = (char *)malloc(transfer_size + 2);
while (bytes_to_send > 0) {
if (transfer_size > bytes_to_send ) {
transfer_size = bytes_to_send;
}
size_t t = fread(c, 1, transfer_size, fp);
if (bytes_to_send == total_size) {
gettimeofday(&tvB, NULL);
}
bytes_sent = send(n->sock, c, transfer_size, 1);
if (bytes_sent <=0) {
// error
printf("SENDING ERROR\n\n");
break;
}
bytes_to_send -= bytes_sent;
pos = total_size - bytes_to_send;
printf("bytes_sent: %d bytes_to_send: %d\n\n", bytes_sent, bytes_to_send);
fseek(fp, pos, SEEK_SET);
memset(c, 0, transfer_size * sizeof(char));
}
我的问题是recv是
A.) 没有获取我发送的所有文件的最后一个字节,并且
B.) 尽管 send 说它已经发送了所有内容,但它并没有每次都收到整个“ block ”。
为了获得更多信息,这里是运行小文件传输的输出。
接收方:
Size: 38, Filename: hi.txt
SIZE: 1 bytes_read = 37 CHUNK: 38
TotalSize - size 37
发送方:
bytes_sent: 38 bytes_to_send: 0
Successfully sent hi.txt to dest
最佳答案
A 是因为您从未关闭发送者中的套接字。
B 是因为它没有指定以这种方式工作。
您应该发送 t
字节,而不是 transfer_size
字节。
关于c - Recv() 没有得到 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42306504/