2011-05-16 96 views
0

我正在创建一个非常简单的网络服务器,就像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个字符自己。怎么可能?对于某些功能他们只接受一定的长度是否有某种限制?

回答

2

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

+0

所以ios ::二进制我猜?但是,我怎么知道什么尺寸“足够大”? – Emil 2011-05-16 18:25:37

+0

@Emil:读取数据块直到您点击EOF。肯定有更好的方法,但我不太了解C++:P – BlackBear 2011-05-16 18:28:01

+0

@Emil:或者看看这里(第一个google结果)http://www.cplusplus.com/forum/windows/10853/ – BlackBear 2011-05-16 18:36:13

0

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

相关问题