c - Recv() 没有得到 EOF?

标签 c sockets send recv

我正在尝试使用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/

相关文章:

C:访问全局变量或传递指向函数的指针哪个更快

c - c中的逻辑运算和预递增

Python:在套接字监听连接时显示消息 'Waiting for player...'

java - 棋盘游戏逻辑的持久套接字 (Android)

linux - Socket Send(2) - 如何从服务器向客户端发送错误信息

c - 如何使用 C 在 BSD 套接字中处理 3 路 send() 和 receive()

c - 奇怪的 malloc 访问错误

c++ - 从 LLVM IR 获取 C/C++ 源代码数据

sockets - socket recv() 是否强制刷新 socket send() 缓冲区?

javascript - 使用 JSON 和 Ajax 发送不可编辑的数组