I have code where I send file from server to client. The thing is client correctly receives file size from the server, the file (jpeg image), is also recreated with correct file size on the client side, but when I open the image it is displayed half correctly, half is corrupted.
Here is some relevant parts of code. Any idea why this can be happening?
server:
while(1)
{
printf("Waiting to accept connections \n");
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
read_file("/Users/macbookair/Documents/server/server/file1.jpeg", buffer, &length);
// send
write(connfd, &length, 4); // length, 110193 bytes
write(connfd, buffer, length); // file itself
close(connfd);
sleep(1);
}
client:
// open file
FILE * ptrMyFile = fopen("/Users/macbookair/Documents/client/client/file1.jpeg","wb");
if(NULL == ptrMyFile)
{
printf("Unable to open file \n");
return 1;
}
int size = 0;
read(sockfd, &size, 4); // read length first
read(sockfd, buffer, size); // then file
printf("fsize %d\n", size);
// create file
fwrite(buffer, size, 1, ptrMyFile);
fclose(ptrMyFile);
buffer
is of sufficient length. I find weird that correct number of bytes is received, but image is half correctly displayed.