-2
我想上傳文件到服務器,但他們總是損壞,程序非常簡單,只用於在客戶端和服務器之間傳輸文件。 我需要此代碼的幫助,以解決問題。 並改進它。Winsock上傳文件到遠程服務器
SERVER
int Socket_Manip::FILE_UPLOAD() {
//get file size.
iResult = recv(ClientSocket, GotFileSize, LENGTH, 0);
if (iResult == 0)
{
closesocket(ClientSocket);
WSACleanup();
return 1;
}
else if (iResult < 0) {
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//start manip download
long FileSize = atoi(GotFileSize);
long SizeCheck = 0;
char* mfcc;
FILE *fp = fopen("C::\\Users\\Server\\Downloads\\transfer.zip", "wb");
if (fp == NULL)
{
closesocket(ClientSocket);
WSACleanup();
return 1;
}
if (FileSize > 1499) {
mfcc = (char*)malloc(1500);
while (FileSize > SizeCheck){
int Received = recv(ClientSocket, mfcc, 1500, 0);
if (Received == 0)
{
break;
}
else if (Received < 0) {
closesocket(ClientSocket);
WSACleanup();
return 1;
}
SizeCheck += Received;
fwrite(mfcc, 1, Received, fp);
fflush(fp);
}
} else
{
mfcc = (char*)malloc(FileSize + 1);
int Received = recv(ClientSocket, mfcc, FileSize, 0);
fwrite(mfcc, 1, Received, fp);
fflush(fp);
}
fclose(fp);
free(mfcc);
}
CLIENT SENDER
int File_Transfer_Manip() {
FILE *File;
char *Buffer;
unsigned long Size;
File = fopen("C:\\Users\\r4minux\\Downloads\\upload.zip", "rb");
if (!File)
{
printf("Error file\n");
return 1;
}
fseek(File, 0, SEEK_END);
Size = ftell(File);
fseek(File, 0, SEEK_SET);
Buffer = new char[Size];
fread(Buffer, Size, 1, File);
char cSize[MAX_PATH];
sprintf(cSize, "%i", Size);
fclose(File);
iResult = send(ConnectSocket, cSize, MAX_PATH, 0); // File size
if (iResult == SOCKET_ERROR) {
printf("send erroR: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
getchar();
return 1;
}
int Offset = 0;
while (Offset < Size)
{
int Amount = send(ConnectSocket, Buffer + Offset, Size - Offset, 0);
if (Amount <= 0)
{
std::cout << "Error: " << WSAGetLastError() << std::endl;
break;
}
else
{
Offset += Amount;
}
}
// cleanup
free(Buffer);
}
非常感謝您! – Mrdk