如何存储http响应并发送到浏览器? [英] How to store the http response and send to browser?
问题描述
我正在做有关代理服务器的练习。
在代理服务器中缓存时遇到一些问题。
服务器将响应发送给代理并将代理转发给客户端时,将使用以下源代码。没关系。
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;
}
但是当我尝试将HTTP响应写入文件然后读取所有字符时从文件发送到客户端,我有问题。
浏览器说:ERR_CONTENT_DECODING_FAILED
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
我正在测试代理缓存的工作方式,但我不知道哪里出错了。
即使我创建了一个字符串Temp(Data),并使用send(*(P-> CLIENT),Temp.c_str(),length,0),客户端仍然会说该错误。
请帮助我。 :D
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;
}
推荐答案
还有一些问题。
更新:看来您已经对通讯进行了排序,所以我删除了运球。
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通过指出File<<数据未将指针数据的全部内容写入文件。 <<操作员不知道要写入的数据长度。另外,<<运算符具有char *重载。请参阅: http://www.cplusplus.com/reference/ostream / ostream / operator%3C%3C /
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/
我假设数据是一个char *。
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....
这篇关于如何存储http响应并发送到浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!