Winsockets - 身体之前和/或之后的奇怪角色

时间:2018-01-09 15:10:15

标签: php c++ winsock2

我在我的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"; ?>

我不知道它是否是服务器问题,但如果将文本更改为&#34; hello2 PHP&#34;,则返回我的winsock代码,如下所示:

a
hello2 PHP

我无能为力

1 个答案:

答案 0 :(得分:1)

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

Date        Product         Total_Sales_in_Units    Total_Sales USD
1/1/2016    BM-XN           
1/3/2016    VQR-GG2         
1/4/2016    VQR-GG2         
1/6/2016    PIB-H20         
...
  

每个块以其嵌入的数据的八位字节数开始,表示为ASCII中的十六进制数,后跟可选参数(块扩展)和终止CRLF序列,后跟块数据。该块由CRLF终止。