2017-02-17 78 views
0

我想通過send()和recv()發送套接字TCP。爲了測試,我發送了一個38字節的小文本文件。我收到使用此文件:Recv()沒有得到EOF?

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 
+0

我知道,這就是爲什麼我把它放在一個循環中,並通過每個循環的recv()讀取的字節數減少剩餘的字節來讀取。 –

回答

1

A是因爲你從來沒有關閉發件人插座。

B是因爲它沒有被指定爲以這種方式工作。

您應該發送t字節,而不是transfer_size字節。