c++ - 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 文件(正文)。并且有一个奇怪的角色代替它。为什么会这样?它与空字符有关吗?
解决方案
但是,根本不发送 html 文件(正文)。并且有一个奇怪的角色代替它。为什么会这样?
身体被发送,但被压缩。下面告诉你内容是使用gzip
算法压缩的:
Content-Encoding: gzip
您需要解压缩它(注意 NUL 字符)或告诉服务器您不准备处理gzip
编码内容(即删除Accept-Encoding
请求中的标头)。
推荐阅读
- android - 从子片段在父导航图中导航
- spring-boot - 性能测试 - 尽管 API 只返回一个空字符串,但 TPS 还是慢了下来?
- openstack - openstack-victoria (packstack) 实例创建错误
- python - Python中PHP的 :: 相当于什么?
- tensorflow - 更改从 SavedModel 格式加载的子类 Keras 模型的输入形状
- mongodb - 如何在单个插入中在文档的其他字段中使用生成的 id
- python - 使用 Python 连接字符串参数
- c - K&R c 书籍第 5.2 节 getint 示例
- xcode - 在 iOS 上我应该检查什么,并且我的本地化字符串没有被本地化?
- java - 0/1背包算法的解释