2012-11-03 175 views
2

我正在創建簡單的Socket服務器。 Flex應用程序將成爲此服務器的客戶端。根據特殊要求,我需要通過套接字將服務器上的圖像文件(jpeg)傳輸到客戶端。通過SOCKET發送文件

爲了測試目的,我已經在C#上編寫了服務器 - 並且它對我的flex應用程序工作正常。

C#代碼,其中發送的圖像:

private void sendImage(Socket client) 
     { 
      Bitmap data = new Bitmap("assets/sphere.jpg"); 
      Image img = data; 
      MemoryStream ms = new MemoryStream(); 
      img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
      byte[] buffer = ms.ToArray(); 
      sendInt(client, buffer.Length); 
      client.Send(buffer); 
      Console.WriteLine("Image sent"); 
     } 

C++代碼,它發送相同的圖像:

void SocketServer::sendFile(SOCKET &client, std::string filename) 
{ 
    std::ifstream file (filename, std::ios::ate); 
    if (file.is_open()) 
    { 
     std::ifstream::pos_type size = file.tellg(); 
     char * memblock = new char [size]; 
     file.seekg (0, std::ios::beg); 
     file.read (memblock, size); 
     file.close(); 
     sendInt(client, size); 
     send(client, memblock, size, 0); 
     delete[] memblock; 
    } 
} 

send方法返回適當的圖像尺寸發送值。

出於某種原因,我不能在Adobe Flash Builder中4.6調試在Windows 8上,所以我創建輸出插件在那裏我可以看到作爲字符串傳輸結果

C#轉移的結果: enter image description here

C++轉移結果: enter image description here

正如你所看到的500左右第一個字符是相同的。 C++的其餘部分是那些'我'符號。奇怪的是,如果我讀文件轉換成字符串使用這段代碼,例如:

std::ifstream ifs("sphere.jpg"); 
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); 

我的字符串將代替〜124Kbytes的500個字符(〜124K字符,圖像文件大小)。

這裏是C++的圖像結果: enter image description here

所以,我真的不知道爲什麼插座傳輸的唯一正確jpeg非常小的一部分,其餘的都是錯的?正如我所提到的 - 如果我將字節數組從C#傳輸到Flex,沒有任何問題,所以我認爲Flex一切都很好。

+0

client.Send()的返回值是什麼? –

+0

@NathanMoinvaziri它等於buffer.length()或〜124K - 確切的圖像文件大小。 – GuardianX

+1

打開文件時,您是否明確嘗試過使用二進制打開模式? –

回答

1

這可能是由於您沒有明確以二進制模式打開文件。嘗試使用:

std::ifstream file (filename, std::ios::ate | std::ios::binary);