首页 > 解决方案 > Linux socket read() 无法正确读取响应体

问题描述

int proxyRequest(string &request, char buffer[], struct hostent* host){
    int sockfd, sockopt;
    struct sockaddr_in their_addr;
    if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
        perror("Socket generating failed");
        return -1;
    }
    if(host==NULL){
        strcpy(buffer, "HTTP/1.1 404 Not found\r\nContent-Type: text/html\r\n\r\n<h2>INET_E_RESOURCE_NOT_FOUND</h2>");
    }
    else{
        their_addr.sin_family = AF_INET;
        their_addr.sin_port = htons(SERVERPORT);
        their_addr.sin_addr.s_addr = ((struct in_addr*)host->h_addr_list[0])->s_addr;
        if(connect(sockfd, (struct sockaddr*)&their_addr, sizeof(their_addr)) == -1){
            perror("Connection failed");
            return -1;
        }
        write(sockfd, request.c_str(), request.length());
        read(sockfd, buffer, BUFSIZE);
        cout << buffer << endl;
    }
    close(sockfd);
    return 0;
}

我正在制作一个简单的代理服务器,一切都很好,除了我无法收到正确的响应正文。

在此处输入图像描述

这是我发送到服务器(www.example.com)的请求。这在代码中表示为“请求”。

在此处输入图像描述

似乎正确接收了 http 标头。但是,根本不发送 html 文件(正文)。并且有一个奇怪的角色代替它。为什么会这样?它与空字符有关吗?

标签: c++socketsposix

解决方案


但是,根本不发送 html 文件(正文)。并且有一个奇怪的角色代替它。为什么会这样?

身体发送,但被压缩。下面告诉你内容是使用gzip算法压缩的:

Content-Encoding: gzip

您需要解压缩它(注意 NUL 字符)或告诉服务器您不准备处理gzip编码内容(即删除Accept-Encoding请求中的标头)。


推荐阅读