Josh Newlin
Josh Newlin

Reputation: 108

Recv() not getting EOF?

I'm trying to send over socket TCP using send() and recv(). For testing, I'm sending a smaller text file that is 38 bytes. I receive the file using this:

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);

And my sending side:

 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));
 }

My issue is that recv is

A.) Not getting the last byte of all the files I send, and

B.) It's not receiving the whole "chunk" every time, even though send says it has sent everything.

Just for further info, here's the output of running a transfer of a small file.

Receiving side:

Size: 38, Filename: hi.txt

SIZE: 1 bytes_read = 37 CHUNK: 38

TotalSize - size 37

Sending side:

bytes_sent: 38 bytes_to_send: 0

Successfully sent hi.txt to dest

Upvotes: 0

Views: 1419

Answers (1)

user207421
user207421

Reputation: 311052

A is because you're never closing the socket in the sender.

B is because it's not specified to work that way.

You should send t bytes, not transfer_size bytes.

Upvotes: 1

Related Questions