我在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

我的意思是内容之前和之后的 9 0 。我在服务器中的PHP代码如下所示:
<?php echo "hello PHP"; ?>

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

我无能为力

最佳答案

您所看到的是HTTP 1.1 chunked transfer encoding,由服务器在 header 中指定

Transfer-Encoding: chunked

10-02 14:40