如何读取要通过套接字发送的图像?

时间:2011-05-16 18:22:27

标签: c++ image sockets webserver

我正在创建一个非常简单的Web服务器,就像在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个字符清空一次。怎么可能?某些功能是否存在某种限制,只能接受一定的长度?

2 个答案:

答案 0 :(得分:2)

打开文件进行二进制读取,将数据存储在足够大的char *数组中,然后发送该数组。

答案 1 :(得分:0)

正如@Blackbear所说,但不要忘记发送相应的HTML-Headers,如contentEncoding,transferEncoding等。为简单起见,尝试发送base64编码的图像的二进制数据。