gpt4 book ai didi

php - Winsockets - 主体之前和/或之后的奇怪字符

转载 作者:行者123 更新时间:2023-11-30 05:05:51 24 4
gpt4 key购买 nike

我在我的 C++ 项目中使用了一个简单的 winsocket 代码片段,试图从共享主机 (host-ed.me) 上的文件中提取数据。我的 winsocket 代码如下:

void write(string file, string text) {
ofstream os;
os.open(file, ofstream::app);
text += "\n";
os.write(text.c_str(), text.size());
os.close();
}

bool request() {
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char server_reply[4096];
int recv_size;
// initialize winsockets
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
write("log.txt", "winsockets initialization - error!");
return false;
}
// open a socket
if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
write("log.txt", "socket opening - error!");
return false;
}
// connect to server
server.sin_addr.s_addr = inet_addr("46.105.118.169");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0) {
write("log.txt", "server connection - error!");
return false;
}
// send data
string request;
request += "GET /index.php HTTP/1.1\r\n";
request += "Host: machines.host-ed.me\r\n";
request += "Connection: close\r\n";
request += "\r\n";
if (send(s, request.c_str(), request.size(), 0) < 0) {
write("log.txt", "data send - error!");
return false;
}
// receive reply
if ((recv_size = recv(s, server_reply, 4096, 0)) == SOCKET_ERROR) {
write("log.txt", "data receive - error!");
return false;
}
server_reply[recv_size] = '\0';
write("log.txt", string(server_reply)); // gives strange characters
// close socket
closesocket(s);
WSACleanup();
return true;
}

我说的奇怪字符是什么意思,看这个回复:

HTTP/1.1 200 OK
Date: Tue, 09 Jan 2018 15:02:01 GMT
Server: Apache
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html

9
hello PHP
0

我指的是内容前后的 90。我在服务器中的 PHP 代码如下所示:

<?php echo "hello PHP"; ?>

我不知道这是否是服务器问题,但如果将文本更改为“hello2 PHP”,那么它会返回到我的 winsock 代码,如下所示:

a
hello2 PHP

我是傻子

最佳答案

您看到的是 HTTP 1.1 chunked transfer encoding , 正如服务器在 header 中指定的那样

Transfer-Encoding: chunked

Each chunk starts with the number of octets of the data it embeds expressed as a hexadecimal number in ASCII followed by optional parameters (chunk extension) and a terminating CRLF sequence, followed by the chunk data. The chunk is terminated by CRLF.

关于php - Winsockets - 主体之前和/或之后的奇怪字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com