我必须制作一个 http 代理。在代理端,我必须解析用户发送的 http 请求。
问题是:如何从客户端读取二进制数据,最终我会得到一个包含完整请求的 char 数组。
我做的是:每次读取1个字节。
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);
}
最佳答案
阅读单个字符的效率非常低,并且会极大地减慢您的速度。相反,您应该在循环中读取适当大小的 block (1024 似乎与任何初始猜测一样好),并将读取缓冲区附加到到目前为止读取的总数据。使用 C++ std::vector
非常容易做到。
关于c++ - 如何读取一个http请求(一个http代理服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36044266/