2014-02-19 46 views
1

我试图从客户端使用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(); 
     } 
+0

可能分配的memblock太小,意思是 Doberman

+0

BUFFERSIZE当前设置为4096. memblock的大小设置为正在传输的照片的大小。被损坏的照片大小为187786。 – stevetronix

+0

我正在谈论接收器代码中memblock的大小,你不知道那里的图像大小... – Doberman

回答

1
file.write(memblock, FtpThread::BUFFERSIZE); 

应be

file.write(memblock, r); 

你假设recv( )填充缓冲区。

+0

它的工作原理!感谢您花时间帮助! – stevetronix

+0

你必须有比我更好的饲料 - 你总是在我之前得到这些免费赠品:) –