C: Exit client after receiving all data
I am learning sockets for C newbies. I wrote a client-server program to get a file and write it to another file.
The program itself works fine - the file is read by the server correctly, and the client receives it in full, but the client does not exit after receiving all the data.
How does the client know when the whole file is received and how can I close it? Below is a snippet from my client.
Note. I added a condition while (data > 0)
as part of this attempt. Please correct this if it is 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);
source to share
Your server should close the socket after sending all the contents of the file. This will cause your function to recv
return zero and end the client receive loop.
If you want to keep the connection for some reason, you need to first send some additional information to the client (like the length of a file) so that the client knows when one file ends and (potentially) another begins. I'm not sure if you are interested in this.
source to share