How to store the http response and send to browser

2019-08-18 23:21发布

I'm doing an exercise about Proxy Server. I have some problems when caching in Proxy Server. The following source code is used when the server sends a response to proxy and proxy forward it to the client. It's fine.

//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;
}

But when I try to write HTTP response to a file and then read all characters from file to send to the client, I have a problem. browser said: ERR_CONTENT_DECODING_FAILED

I'm testing how does proxy cache work, but I can't understand where is error. Even when i create a string Temp(Data), and use send(*(P->CLIENT), Temp.c_str(), length, 0), client still said that error. Please help me. :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;
}

1条回答
看我几分像从前
2楼-- · 2019-08-18 23:57

A few things stick out.

Update: It looks like you have the communications sorted, so I removed that dribble.

But I think your issue is in the line: File << Data;

VTT is correct by pointing out that File << Data doesn't write the full contents of our pointer Data into the file. The << operator doesn't know the length of the data you want to write. Also, it doesn't appear that the << operator has a char * overload. See: http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

I assume Data is a char * .

Instead of File << Data, try:

 File.write( Data, length);    

And then read it back and write it to the client....

查看更多
登录 后发表回答