我正在創建一個非常簡單的網絡服務器,就像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個字符自己。怎麼可能?對於某些功能他們只接受一定的長度是否有某種限制?
所以ios ::二進制我猜?但是,我怎麼知道什麼尺寸「足夠大」? – Emil 2011-05-16 18:25:37
@Emil:讀取數據塊直到您點擊EOF。肯定有更好的方法,但我不太瞭解C++:P – BlackBear 2011-05-16 18:28:01
@Emil:或者看看這裏(第一個google結果)http://www.cplusplus.com/forum/windows/10853/ – BlackBear 2011-05-16 18:36:13