I'm trying to send an image file through a TCP socket in C, but the image isn't being reassembled correctly on the server side. I was wondering if anyone can point out the mistake?
I know that the server is receiving the correct file size and it constructs a file of that size, but it isn't an image file.
Client
//Get Picture Size
printf("Getting Picture Size\n");
FILE *picture;
picture = fopen(argv[1], "r");
int size;
fseek(picture, 0, SEEK_END);
size = ftell(picture);
//Send Picture Size
printf("Sending Picture Size\n");
write(sock, &size, sizeof(size));
//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
char send_buffer[size];
while(!feof(picture)) {
fread(send_buffer, 1, sizeof(send_buffer), picture);
write(sock, send_buffer, sizeof(send_buffer));
bzero(send_buffer, sizeof(send_buffer));
}
Server
//Read Picture Size
printf("Reading Picture Size\n");
int size;
read(new_sock, &size, sizeof(int));
//Read Picture Byte Array
printf("Reading Picture Byte Array\n");
char p_array[size];
read(new_sock, p_array, size);
//Convert it Back into Picture
printf("Converting Byte Array to Picture\n");
FILE *image;
image = fopen("c1.png", "w");
fwrite(p_array, 1, sizeof(p_array), image);
fclose(image);
Edit: Fixed sizeof(int) in server code.
Many peoples found it difficult to do it. many times we need to send images through network socket from one computer to another computer. Now we are going to see how we can send image through socket in java.
A better way to send the image would be to use BinaryFormatter. eg, some snippets from my own code to send an image every second... TcpClient client = new TcpClient (); try { client.Connect (address, port); // Retrieve the network stream.
User starts server with a button and client selects photo by opening the file dialog of computer. At last sends the image but be careful about the photo size because UDP cannot transmit much large data.
At last sends the image but be careful about the photo size because UDP cannot transmit much large data.
you need to seek to the beginning of the file before you read
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
or use fstat
to get the file size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With