简体   繁体   中英

how to read an http request(an http proxy server)

I have to make an http proxy. In the proxy side I have to parse the http request sent by the user.

The question is: How to read binary data from the client such at the final I will get an array of char that contains the full request .

What I did is: Read 1 Byte each time.

    char c;
    int  n = read(con,&c,1);

I saw many implementation where we use 1024 bytes as the size of the buffer , but are we sure that the size of the request will not exceeds 1024?

Normally in first place I have to allocate the memory for the buffer array , so how can i know the size of the request to allocate the same size of memory?

My full methods:

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

Reading by a single character is terribly inefficient and slows you down tremendously. Instead, you should be reading by chunks of approriate size (1024 seems as good initial guess as any) in the loop and append read buffer to the total data read so far. It is extremely easy to do with C++ std::vector .

解析 HTTP 请求是一项相当复杂的任务,我认为使用像http-parser这样的库会更容易,它以非常有效的方式为您解析。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM