저는 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 :: binary로 열렸지만 더 많은 문제가 있습니다.
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 :: binary 같네요?. 그러나 어떤 크기가 "충분히 큰"것인지 어떻게 알 수 있습니까? – Emil
@Emil : EOF에 도달 할 때까지 데이터 청크를 읽습니다. 확실하게 더 좋은 방법이지만 C++을 잘 모른다 : P – BlackBear
@Emil : 여기를 보거나 (첫 번째 Google 결과) http://www.cplusplus.com/forum/windows/10853/ – BlackBear