客户端向服务器发送文件出错

Sending file from client to server goes wrong

我尝试从客户端向服务器发送 .jpeg 文件。每次我在客户端读取一个字节时,我都会立即将它发送到我的服务器并将其写入文件。文件创建成功,但是当我打开新图像时它不查看它。如何才能成功发送文件?

服务器:

char buf[BUFSIZ]; // Array where the read objects are stored
FILE* copyFile; // Write to this
fopen_s(&copyFile, "C:\Users\name\Documents\img3.jpeg", "wb");

while (1)
{
    recv(s, buf, BUFSIZ, 0);
    fwrite(buf, 1, BUFSIZ, copyFile);
}
fclose(copyFile);

客户:

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);

您忽略了 fread()/fwrite()send()/recv() 的 return 值。它们分别告诉您实际 read/written 和 sent/received 有多少字节。永远不要忽略系统调用的 return 值。

试试这个:

服务器:

FILE* copyFile; // Write to this
if (fopen_s(&copyFile, "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);
}

客户:

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);
}