Linux socket read() 无法正确读取响应 body
Linux socket read() can not read the response body correctly
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;
}
我正在制作一个简单的代理服务器,一切都很好,除了我无法收到正确的响应 body。
这是我发送给服务器的请求(www.example.com)。这在代码中表示为 "request"。
似乎正确接收了 http headers。但是,根本没有发送 html 文件 (body)。取而代之的是一个奇怪的角色。为什么会这样?与空字符有关吗?
However, the html file(body) is not sent at all. And there is a weird character instead of it. Why does this happen?
body已发送,但已压缩。下面告诉你内容是使用gzip
算法压缩的:
Content-Encoding: gzip
您需要解压缩它(注意 NUL 字符)或告诉服务器您不准备处理 gzip
编码的内容(即删除 Accept-Encoding
header 在你的请求中)。
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;
}
我正在制作一个简单的代理服务器,一切都很好,除了我无法收到正确的响应 body。
这是我发送给服务器的请求(www.example.com)。这在代码中表示为 "request"。
似乎正确接收了 http headers。但是,根本没有发送 html 文件 (body)。取而代之的是一个奇怪的角色。为什么会这样?与空字符有关吗?
However, the html file(body) is not sent at all. And there is a weird character instead of it. Why does this happen?
body已发送,但已压缩。下面告诉你内容是使用gzip
算法压缩的:
Content-Encoding: gzip
您需要解压缩它(注意 NUL 字符)或告诉服务器您不准备处理 gzip
编码的内容(即删除 Accept-Encoding
header 在你的请求中)。