我嘗試將 .jpeg 檔案從客戶端發送到服務器。每次我在客戶端讀取一個位元組時,我都會立即將其發送到我的服務器并將其寫入檔案。檔案創建成功,但是當我打開新影像時,它看不到它。如何成功發送檔案?
服務器:
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);
客戶:
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);
uj5u.com熱心網友回復:
您忽略了fread()/fwrite()和send()/的回傳值recv()。它們分別告訴您實際讀取/寫入和發送/接收了多少位元組。永遠不要忽略系統呼叫的回傳值。
試試這個:
服務器:
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);
}
客戶:
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/443993.html
