Reputation: 1045
I am creating a very simple webserver, as practice in C++ and sockets. I use OSX.
The code sample is from inside the while(1) loop, a connection has been made and I am starting to process the header. This code works for all text-files but it dosn't work with images. And I figure that I can't use the same method to read text-files and images since images isn't separeted with lines. But how do I read the image data to send through the socket? I might not even be able to use a string, do I have to use 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
The question is about how to read the image data.
*EDIT 2011-05-19 *
So, this is an updated version of my code. The file have been opened with ios::binary, however, there are more problems.
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++;
}
The problem is that is seems that the char * fileContents empty itself every ~240 chars. How can that be? Is there some sort of limit to some of theese functions that they only accept certain length?
Upvotes: 0
Views: 340
Reputation: 126
As @Blackbear said, but don't forget to send the corresponding HTML-Headers like contentEncoding, transferEncoding, etc. For simplicity try to send the binary Data of the image encoded in base64.
Upvotes: 0
Reputation: 22979
Open the file for binary read, store the data in a char* array large enough, then send that array.
Upvotes: 2