如何读取通过套接字发送的图像? 我创建了一个非常简单的Web服务器,如C++和套接字的实践。我使用OSX
代码示例来自while(1)循环内部,已经建立了连接,我开始处理标头。此代码适用于所有文本文件,但不适用于图像。我想我不能用同样的方法来读取文本文件和图像,因为图像不是用线分隔的。但是如何读取通过套接字发送的图像数据呢?我甚至可能不能使用字符串,我必须使用char*如何读取通过套接字发送的图像? 我创建了一个非常简单的Web服务器,如C++和套接字的实践。我使用OSX,c++,image,sockets,webserver,C++,Image,Sockets,Webserver,代码示例来自while(1)循环内部,已经建立了连接,我开始处理标头。此代码适用于所有文本文件,但不适用于图像。我想我不能用同样的方法来读取文本文件和图像,因为图像不是用线分隔的。但是如何读取通过套接字发送的图像数据呢?我甚至可能不能使用字符串,我必须使用char* string strFile = "htdocs" + getFileFromHeader(httpRequestHeader); string strExt = getFileExtension(strFil
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
string strFile=“htdocs”+getFileFromHeader(httpRequestHeader);
string strExt=getFileExtension(strFile);
字符串httpContent=“”;
ifstream fileIn(strFile.c_str(),ios::in);// 打开文件进行二进制读取,将数据存储在一个足够大的char*数组中,然后发送该数组。正如@Blackbear所说,但不要忘记发送相应的HTML头,如contentEncoding、transferEncoding等。为简单起见,请尝试发送用base64编码的图像的二进制数据。我想是ios::binary吗?。但是我怎么知道“足够大”的大小呢?@Emil:读取数据块,直到达到EOF。肯定有更好的方法,但我不太清楚C++。P@Emil:或查看此处(第一个谷歌结果)
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++;
}