I try to send a .jpeg file from client to server. Everytime I read a byte in my client I immediatley send it to my server and write it to the file. The file creation goes successfully but when I open the new image it doesn't view it. How can I send a file successfully?
server:
char buf[BUFSIZ]; // Array where the read objects are stored
FILE* copyFile; // Write to this
fopen_s(©File, "C:\\Users\\name\\Documents\\img3.jpeg", "wb");
while (1)
{
recv(s, buf, BUFSIZ, 0);
fwrite(buf, 1, BUFSIZ, copyFile);
}
fclose(copyFile);
client:
char buf[BUFSIZ]; // Array where the read objects are stored
size_t size = BUFSIZ;
FILE* originalFile; // Read from this
fopen_s(&originalFile, "C:\\Users\\name\\Documents\\img.jpeg", "rb");
while (size == BUFSIZ)
{
size = fread(buf, 1, BUFSIZ, originalFile);
send(ClientSocket, buf, 1, 0);
}
fclose(originalFile);
CodePudding user response:
You are ignoring the return values of both fread()
/fwrite()
and send()
/recv()
. They tell you how many bytes were actually read/written and sent/received, respectively. Never ignore the return values of system calls.
Try this instead:
server:
FILE* copyFile; // Write to this
if (fopen_s(©File, "C:\\Users\\name\\Documents\\img3.jpeg", "wb") == 0)
{
char buf[BUFSIZ]; // Array where the read objects are stored
int numRecvd;
while ((numRecvd = recv(s, buf, sizeof(buf), 0)) > 0)
{
if (fwrite(buf, numRecvd, 1, copyFile) != 1) break;
}
fclose(copyFile);
}
client:
FILE* originalFile; // Read from this
if (fopen_s(&originalFile, "C:\\Users\\name\\Documents\\img.jpeg", "rb") == 0)
{
char buf[BUFSIZ]; // Array where the read objects are stored
size_t size;
while ((size = fread(buf, 1, sizeof(buf), originalFile)) > 0)
{
char *ptr = buf;
do {
int numSent = send(ClientSocket, ptr, size, 0);
if (numSent < 0) break;
ptr = numSent;
size -= numSent;
}
while (size > 0);
if (size != 0) break;
}
fclose(originalFile);
}