这是我的问题,我在同一台机器上测试了客户端和服务器的文件传输功能,一切正常。
但是当我尝试在不同的机器上本地使用它时,我收到的文件已损坏。大小似乎是相同的,但当我用十六进制编辑器打开它时,文件略有不同(截图:http://i.imgur.com/9YNFNxx.png)
服务器
void fileSend(SOCKET theSocket, string filePath)
{
ifstream fichier;
fichier.open(filePath, ios::binary);
int cumul = 0;
int size = BUFF_SIZE;
char szBuf[BUFF_SIZE];
int nRet;
//Used to find and send the size of the file
fichier.seekg(0, ios::end);
int taille = fichier.tellg();
// int --> char*
sprintf_s(szBuf, "%d", taille);
nRet = send(theSocket, // Connected socket
szBuf, // Data buffer
sizeof(szBuf), // Buffer length
0); // Flags
fichier.seekg(0, ios::beg);
// Send Packets of size 256 per (BUFF_SIZE)
while (cumul < taille)
{
//Adjust when we are at the last packet
if ((taille - cumul) < BUFF_SIZE)
size = (taille - cumul);
fichier.read(szBuf, size);
// Send the Packet
nRet = send(theSocket, // Connected socket
szBuf, // Data buffer
size, // Buffer length
0); // Flags
if (nRet != -1)
cumul += nRet;
memset(szBuf, 0, sizeof(szBuf));
}
fichier.close();
}
客户端
void fileReceive(SOCKET theSocket, char* fileName)
{
ofstream fichier;
fichier.open(fileName, ios::binary | ios::beg);
int cumul = 0;
int size = BUFF_SIZE;
char szBuf[BUFF_SIZE];
int nRet;
// We receive the size of the File
nRet = recv(theSocket, // Connected socket
szBuf, // Receive buffer
sizeof(szBuf), // Size of receive buffer
0); // Flags
if (nRet == SOCKET_ERROR)
{
closesocket(theSocket);
return;
}
// Char* -> int
int taille = atoi(szBuf);
// Receive Packets per size of 256 (BUFF_SIZE)
while (cumul < taille)
{
//When on the last Packet, adjust size
if ((taille - cumul) < BUFF_SIZE)
size = (taille - cumul);
// Recevoir le paquet
nRet = recv(theSocket, // Connected socket
szBuf, // Data buffer
size, // Lenght of data
0); // Flags
if (nRet != -1)
{
cumul += nRet;
fichier.write(szBuf, size);
}
memset(szBuf, 0, sizeof(szBuf));
}
fichier.close();
}