2011-05-16 68 views
0

我正在創建一個非常簡單的網絡服務器,就像C++和套接字中的練習一樣。我使用OSX。如何讀取要通過套接字發送的圖像?

代碼示例來自while(1)循環內部,已建立連接並開始處理標題。此代碼適用於所有文本文件,但不適用於圖像。而且我認爲我不能使用相同的方法來讀取文本文件和圖像,因爲圖像沒有用線條分隔。但是,如何讀取通過套接字發送的圖像數據?我甚至可能無法使用字符串,我必須使用char *嗎?

string strFile = "htdocs" + getFileFromHeader(httpRequestHeader); 
    string strExt = getFileExtension(strFile); 

    string httpContent = ""; 
    ifstream fileIn(strFile.c_str(), ios::in); // <-- do I have to use ios::binary ? 

    if(!fileIn) 
    { 
     // 404 
     cout << "File could not be opened" << endl; 
     httpContent = httpHeader404; 
    } 
    else 
    { 
     // 200 
     string contentType = getContentType(strExt); 
     cout << "Sending " << strFile << " -- " << contentType << endl; 
     string textInFile = ""; 

     while (fileIn.good()) 
     { 
      getline (fileIn, textInFile); // replace with what? 
      httpContent = httpContent + textInFile + "\n"; 
     } 

     httpContent = httpHeader200 + newLine + contentType + newLine + newLine + httpContent; 
    } 
    // Sending httpContent through the socket 

問題是關於如何讀取圖像數據。

* 編輯2011-05-19 *

所以,這是我的代碼的更新版本。該文件已被打開與ios ::二進制,但是,還有更多的問題。

httpContent = httpHeader200 + newLine + contentType + newLine + newLine; 
char* fileContents = (char*)httpContent.c_str(); 
char a[1]; 
int i = 0; 

while(!fileIn.eof()) 
{ 
    fileIn.read(a, 1); 

    std::size_t len = std::strlen (fileContents); 
    char *ret = new char[len + 2]; 

    std::strcpy (ret, fileContents); 
    ret[len] = a[0]; 
    ret[len + 1] = '\0'; 

    fileContents = ret; 

    cout << fileContents << endl << endl << endl; 

    delete [] ret; 

    i++; 
} 

問題是,似乎char * fileContents每空出約240個字符自己。怎麼可能?對於某些功能他們只接受一定的長度是否有某種限制?

回答

2

打開文件進行二進制讀取,將數據存儲在足夠大的char *數組中,然後發送該數組。

+0

所以ios ::二進制我猜?但是,我怎麼知道什麼尺寸「足夠大」? – Emil 2011-05-16 18:25:37

+0

@Emil:讀取數據塊直到您點擊EOF。肯定有更好的方法,但我不太瞭解C++:P – BlackBear 2011-05-16 18:28:01

+0

@Emil:或者看看這裏(第一個google結果)http://www.cplusplus.com/forum/windows/10853/ – BlackBear 2011-05-16 18:36:13

0

正如@Blackbear所說的,但不要忘記發送像contentEncoding,transferEncoding等相應的HTML標題。爲了簡單起見,請嘗試發送以base64編碼的圖像的二進制數據。