C++ 如何读取http请求(http代理服务器)
我必须做一个http代理。在代理端,我必须解析用户发送的http请求 问题是:如何从客户端读取二进制数据,例如在最后我将得到一个包含完整请求的char数组 我所做的是:每次读取1字节C++ 如何读取http请求(http代理服务器),c++,c,sockets,http,pointers,C++,C,Sockets,Http,Pointers,我必须做一个http代理。在代理端,我必须解析用户发送的http请求 问题是:如何从客户端读取二进制数据,例如在最后我将得到一个包含完整请求的char数组 我所做的是:每次读取1字节 char c; int n = read(con,&c,1); 我看到许多实现使用1024字节作为缓冲区的大小,但是我们确定请求的大小不会超过1024吗 通常首先我必须为缓冲区数组分配内存,那么我如何知道分配相同大小内存的请求的大小呢 我的全部方法: void readToken(int
char c;
int n = read(con,&c,1);
我看到许多实现使用1024字节作为缓冲区的大小,但是我们确定请求的大小不会超过1024吗 通常首先我必须为缓冲区数组分配内存,那么我如何知道分配相同大小内存的请求的大小呢 我的全部方法:
void readToken(int con,char *token){
char c;
int i=0;
do{
int n = read(con,&c,1);
*token++ = c;
}while(c!=' ' && c!='\n');
}
void readLine(int con,char *line){
char c;int i=0;
do{
int n = read(con,&c,1);
*line++ = c;
}while(c!='\n');
}
char * handleRequest(int con){
char resource[30];
char version[5];
char method[4] ;
//i read 4 byte to get the method tyepe
int n = read(con,&method,4);
//here i read until i get a blank space
readToken(con,resource);
//readToken(con,version);
printf("the method is%s\n",method);
printf("the resource asked is%s\n",resource);
//printf("the resource asked is%s\n",version);
printf("the method read is %s",firstLine);
readLine(con,hostLine);
printf("the method read is %s",hostLine);
}
一个字的阅读效率极低,速度也极慢。相反,您应该在循环中按适当大小的块(1024看起来和任何初始猜测一样好)进行读取,并将读取缓冲区附加到迄今为止读取的总数据中。使用C++ +代码> STD::向量非常简单。 < P>解析HTTP请求是一项相当复杂的任务,我认为使用一个类库更容易,这对你来说是非常有效的解析。“我们确信请求的大小不会超过1024吗?”没有。如果我没记错的话,标准上没有提到尺寸。浏览器限制在4到11kbs之间。缓冲区应该只是为了提高读取效率。您应该在循环中不断填充缓冲区,直到收到整个请求(或超时/错误等)。谢谢,我如何在C中附加新的传入数据?我想如果我循环并读取缓冲区,我会覆盖前面的数据。@jeanjack,在C中,你必须使用类似
realloc
的东西来不断增加缓冲区的大小。