【问题标题】:Recv() not getting EOF?Recv() 没有得到 EOF?
【发布时间】:2017-07-07 11:39:38
【问题描述】:

我正在尝试使用 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 说它已经发送了所有内容。

仅供参考,这里是运行小文件传输的输出。

接收方:

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

【问题讨论】:

  • 我明白,这就是为什么我将它放在一个循环中,并根据 recv() 每次循环读取的字节数递减要读取的剩余字节数。

标签: c sockets send recv


【解决方案1】:

A 是因为您从不关闭发送方的套接字。

B 是因为它没有指定以这种方式工作。

您应该发送t 字节,而不是transfer_size 字节。

【讨论】:

    猜你喜欢
    • 2011-11-29
    • 2021-09-17
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多