我試圖從客戶端使用C++中的套接字將二進制JPEG文件放入服務器。大多數時候JPEG文件都可以正常傳輸。但是,有時候它會以較大的文件大小進行傳輸,並且該照片具有像素化部分。可能是什麼問題?二進制JPEG文件使用套接字損壞()
這是我在服務器端代碼,使用的recv():
void FtpThread::CPut(std::vector<std::string>& Arguments)
{
//filesize of file being put on server
const int size = atoi(Arguments[2].c_str());
char *memblock;
memblock = new char[size];
//Sets memblock to 0's
memset(memblock, 0, size);
//send client a confirmation - 150 ok to send data
send(s, Ftp::R150_PUT.c_str(), Ftp::R150_PUT.length(), 0);
//stores the return value of recv()
int r;
char currentPath[FILENAME_MAX];
std::string filePath;
//gets the full path of the current working directory
_getcwd(currentPath, sizeof(currentPath)/sizeof(TCHAR));
filePath = currentPath + std::string("\\") + FtpThread::FILE_DIRECTORY + std::string("\\") + Arguments[1];
//open file (output file stream)
std::ofstream file(filePath, std::ios::out|std::ios::binary|std::ios::trunc);
if (file.is_open())
{
//while memory blocks are still being received
while ((r = recv(ds, memblock, FtpThread::BUFFERSIZE, 0)) != 0)
{
//if there's a socket error, abort
if (r == SOCKET_ERROR)
{
std::cerr << "WSA Error Code:" << WSAGetLastError() << std::endl;
//send client "Requested action aborted. Local error in processing."
send(s, Ftp::R451.c_str(), Ftp::R451.length(), 0);
file.close();
closesocket(ds);
return;
}
//write client's file blocks to file on server
file.write(memblock, FtpThread::BUFFERSIZE);
}
closesocket(ds);
delete[] memblock;
//finished sending memory blocks; file is completely transferred.
file.close();
//let client know "226 File send OK"
send(s, Ftp::R226_PUT.c_str(), Ftp::R226_PUT.length(), 0);
}
else //if no such file exists on server - send a "550 Failed to open file"
{
send(s, Ftp::R550.c_str(), Ftp::R550.length(), 0);
}
}
這是我對使用send()方法的客戶端代碼:
std::ifstream::pos_type size;
char* memblock;
std::ifstream file(filename, std::ios::in|std::ios::binary|std::ios::ate);
if (file.is_open())
{
size = file.tellg();
if(size > 0)
{
memblock = new char[size];
file.seekg(0, std::ios::beg);
file.read(memblock, size);
file.close();
sendData(memblock, size);
delete[] memblock;
}
closesocket(sockData);
handleResponse();
}
可能分配的memblock太小,意思是
Doberman
BUFFERSIZE當前設置爲4096. memblock的大小設置爲正在傳輸的照片的大小。被損壞的照片大小爲187786。 – stevetronix
我正在談論接收器代碼中memblock的大小,你不知道那裏的圖像大小... – Doberman