C sockets: Exit client after all data is received

575 Views Asked by At

I am a C newbie learning sockets. I wrote a client-server program to receive a file and write it to another file.

The program itself works fine - the file is read by server properly and the client receives it in full, but the client does not exit after receiving all the data.

How would the client know when the entire file is received and how do I make it exit? Following is my client snippet.

Note: I added the condition while (data > 0) as a part of this attempt. Please correct this if wrong.

#define BUFFER 2048
char recived_data[BUFFER];
bzero(recived_data, BUFFER);
FILE *new_file = fopen(“Test.jpg”, “w”);
int data;
do {
    data = recv(sockfd, recived_data, BUFFER, 0);
    fwrite(recived_data, 1, sizeof(recived_data), new_file);
} while (data > 0);
2

There are 2 best solutions below

0
On BEST ANSWER

Your server should close the socket after the whole file content has been sent. This would cause your recv function to return zero and end the client's receive loop.

If you want to keep the connection for some reason, then you would need to send some additional information to the client first (e.g. file length) - so the client knows when one file ends and (potentially) another begins. I'm not sure if you are interested in that, though.

0
On

The sender can send the file size before sending the file. The receiver can then receive the file size (say 4 bytes), then call recv() until the full file size has been received.