0

我需要构建一个处理 GET 方法的 HTTP 代理服务器。
我能够建立从客户端(网络浏览器)到代理服务器的连接,并且代理正在将重新格式化的标头发送到服务器并检索响应。
但是代理没有接收到全部数据。

我的代码如下:

main(int argc,char **argv)
 {
//Server binds to particular port
//Waiting for connection");
for(;;)
{
     //Connect to client
    handle_connection(connfd,&cli_addr);
    close(connfd);

}
}
void handle_connection(int connfd, struct sockaddr_in *cli_addr)
{
struct sockaddr_in host_addr;
char buffer[BUFFSIZE];
int rfd,n;
char** http_args;
url* requested_url;
struct hostent *hp;

bzero(buffer, BUFFSIZE);

if ((rfd = read(connfd,buffer,BUFFSIZE)) < 0 ) {
    perror("Error reading from socket.");
    return;
}
buffer[rfd]='\0';

split_line( (char*)buffer, (char**)http_args,2);
requested_url = parse_request(http_args[1]);

//Printing
    printf("\nCommand: %s\n", http_args[0]);
    printf("Url: %s\n", http_args[1]);
    printf("proto: %d\n",requested_url->proto);
    printf("port: %d\n",requested_url->port);
    printf("host: %s\n",requested_url->host);
    printf("File: %s\n",requested_url->file);


if((strcmp(http_args[0],"GET"))!=0)
{
printf("here");
http_error_messages(connfd, http_args[0], 501, "Not Implemented","Proxy does not implement this method");
return;
}

//Connection to request made to server on rfd 
sprintf(buffer, "%s %s HTTP/1.%d\r\nHost: %s:80\r\n\r\n"
        , http_args[0], requested_url->file, requested_url->proto, requested_url->host);
printf("In the Server %s",buffer);
//printf("In the Server %s",get_header);
n = write(rfd,buffer,sizeof(buffer));
shutdown(rfd,2);

char buff[MAXLINE];
while((n = read(rfd, buff, MAXLINE)) > 0) {
    write(connfd, buff, MAXLINE);
    printf("%s",buff);
    }
    if(n<0)
    {
    perror("Error in reading");
    }
    shutdown(rfd,1);
    shutdown(connfd,2);

close(rfd); 

 }
4

1 回答 1

1

在 TCP 套接字上,您需要read()重复调​​用,直到读取到预期的终止字符 ( \n?),或者读取了所需的字节数。

read()可以返回部分数据或不返回数据,具体取决于 TCP 数据包如何分段/缓冲/混淆。

于 2012-10-31T16:59:33.420 回答