【问题标题】:Receiving data from remote server从远程服务器接收数据
【发布时间】:2012-05-14 22:08:45
【问题描述】:

我在从远程服务器接收数据时遇到问题。似乎可以向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) 您需要在写入结果之前检查读取错误 (if(readsize &lt;= 0)),而不是之后。 (2) 请出示设置requestBuf的代码。特别是sizeof(requestBuf)的使用看起来很可疑,因为请求不太可能占据整个缓冲区。 (3) recBuf 不是 NUL 终止的,因此您不能像在 cout.flush() &lt;&lt; recBuf &lt;&lt; endl; 行中那样对待它。
  • 我包含了建议 (1)。添加了更多关于如何设置 requestBuf 的代码(很难显示 requestBuf 是如何完全设置的,有一个完整的 API 提供给我)
  • 不把recBuf当作NUL终止,我可以加一个\0吗?
  • 从技术上讲,不,因为它可能嵌入了 NUL。使用从read 返回的长度,就像在write 系统调用中一样。例如,fwrite(recBuf, 1, readSize, stdout)(这是一个 C 样式的 stdio 操作,不是 C++,但无论如何你都可以使用它)。

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


【解决方案1】:

在这段代码中:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2015-06-09
    相关资源
    最近更新 更多