Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何读取http请求(http代理服务器)_C++_C_Sockets_Http_Pointers - Fatal编程技术网

C++ 如何读取http请求(http代理服务器)

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

我必须做一个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);       
}

一个字的阅读效率极低,速度也极慢。相反,您应该在循环中按适当大小的块(1024看起来和任何初始猜测一样好)进行读取,并将读取缓冲区附加到迄今为止读取的总数据中。使用C++ +代码> STD::向量非常简单。

< P>解析HTTP请求是一项相当复杂的任务,我认为使用一个类库更容易,这对你来说是非常有效的解析。

“我们确信请求的大小不会超过1024吗?”没有。如果我没记错的话,标准上没有提到尺寸。浏览器限制在4到11kbs之间。缓冲区应该只是为了提高读取效率。您应该在循环中不断填充缓冲区,直到收到整个请求(或超时/错误等)。谢谢,我如何在C中附加新的传入数据?我想如果我循环并读取缓冲区,我会覆盖前面的数据。@jeanjack,在C中,你必须使用类似
realloc
的东西来不断增加缓冲区的大小。