如何存储 http 响应并发送到浏览器

How to store the http response and send to browser?

本文关键字:并发 响应 浏览器 http 何存储 存储      更新时间:2023-10-16

我正在做一个关于代理服务器的练习。我在代理服务器中缓存时遇到了一些问题。当服务器向代理发送响应并将其转发到客户端时,使用以下源代码。没事的。

//that code is ok
fstream File;
while (P->isClientClose == FALSE && P->isServerClose == FALSE){
    memset(Data, 0, 1024);
    int length = recv(*(P->SERVER), Data, sizeof(Data), 0);
    if (length <= 0)
        break;
    length = send(*(P->CLIENT), Data, length, 0);
    if (length <= 0)
        break;
}

但是当我尝试将 HTTP 响应写入文件,然后从文件中读取所有字符以发送到客户端时,我遇到了问题。浏览器 说: ERR_CONTENT_DECODING_FAILED

我正在测试代理缓存的工作原理,但我不明白错误在哪里。即使我创建一个字符串 Temp(Data(,并使用 send(*(P->CLIENT(, Temp.c_str((, length, 0(,客户端仍然说这个错误。请帮助我。:D

//that code is error
fstream File;
while (P->isClientClose == FALSE && P->isServerClose == FALSE){
    memset(Data, 0, 1024);
    int length = recv(*(P->SERVER), Data, sizeof(Data), 0);
    if (length <= 0)
        break;
    File.open("test.dat", ios::out|ios::binary);
    File << Data;
    File.close();
    File.open("test.dat", ios::in|ios::ate|ios::binary);
    ifstream::pos_type pos = File.tellg();
    int size = pos;
    cout << "size: " << size << endl;
    char *pChars = new char[size+1]{};
    File.seekg(0, ios::beg);
    File.read(pChars, size);
    File.close();   
    length = send(*(P->CLIENT), pChars, length, 0);
    delete[]pChars;
    if (length <= 0)
        break;
}

有几件事很突出。

更新:看起来你已经整理了通信,所以我删除了那个运球。

但我认为你的问题出在一线: 文件<<数据;

VTT 是正确的,它指出文件<<数据不会将指针数据的全部内容写入文件。 <<运算符不知道要写入的数据的长度。此外,<<运算符似乎没有 char * 重载。 请参阅: http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

我假设数据是一个字符 * .

尝试以下方法,而不是"文件<<数据":

 File.write( Data, length);    

然后读回并写给客户....