从远程服务器接收数据

时间:2012-05-14 02:49:28

标签: c++ http sockets proxy remote-server

我在从远程服务器接收数据时遇到问题。我似乎可以向http://www.google.com等主机发送HTTP请求,但我无法得到答复。 我正在向主机发送一个HTTP 1.0请求,格式如下:

GET / HTTP / 1.0
主持人:www.google.com
连接:关闭

以下是代理代码的一部分:

    //Parse Request Buffer
    HttpRequest req;
    req.ParseRequest(request.c_str(), request.length());

    //Format Data to be Sent:
    req.AddHeader ("Connection", "close");  // add connection close headers
    req.SetVersion ("1.0");                 // set http 1.0 flag
    char *requestBuf = new char [req.GetTotalLength()];
    req.FormatRequest(requestBuf);

    //Get host IP by name
    struct hostent *host;
    host = gethostbyname(req.GetHost().c_str());

    //Setup remote address structure
    struct sockaddr_in remoteAddr;
    remoteAddr.sin_family = AF_INET;     
    remoteAddr.sin_port = htons(req.GetPort());   
    remoteAddr.sin_addr = *((struct in_addr *)host->h_addr);

    //create new socket for remote server
    int remoteSock = socket(AF_INET, SOCK_STREAM, 0);
    if(remoteSock < 0)
    {
            perror("Socket Error");
            //return -1;
    }

    //connecting to remote server
    if(connect(remoteSock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
    {
            perror("Connect Error");
            //return -1;
    }

    cout.flush() << requestBuf << endl;
    //send request to remote server
    if(send(remoteSock, requestBuf, sizeof(requestBuf), 0) < 0)
    {
            perror("Write Error");
            //return -1;
    }

    //receive reply from server
    char *recBuf = new char [1024];
    int bufSize = 1024;
    int readSize;

    while(1)
    {
            readSize = read(remoteSock, recBuf, bufSize);   //Read from Remote Server
            cout.flush() << recBuf << endl;
            if(readSize <= 0)       //If the requestBuf not filled, nothing left to send to client
                    break;
            write(clientSock, recBuf, readSize);            //write reply to Client

    }

    close(remoteSock);


recBuf的cout.flush()没有输出任何内容 关于最新情况的任何想法?

1 个答案:

答案 0 :(得分:2)

在此代码中:

if(send(remoteSock, requestBuf, sizeof(requestBuf), 0) < 0)

您只向远程端发送(可能)4或8个字节。 requestBuf声明为char *,这是一种指针类型。您需要传递已构建的请求的实际长度,而不是sizeof(requestBuf),而您的情况似乎为req.GetTotalLength()