使用套接字 php 使用端口获取正文内容



>我在下面有代码,它使用套接字接受连接并显示它,然后发回一些标头,但是我看不到已发送给侦听器的正文内容,我只得到代码下方指示的标头,内容长度清楚地表明内容已发送,请帮助

    $host = "192.168.8.121";
    $port = 454;
    // don't timeout!
    set_time_limit(0);
    // create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socketn");
    $result = socket_bind($socket, $host, $port) or die("Could not bind to socketn");
    $result = socket_listen($socket, 3) or die("Could not set up socket listenern");
    do {
       $spawn = socket_accept($socket) or die("Could not accept incoming connectionn");
    // read client input
       $input = socket_read($spawn, 1024) or die("Could not read inputn");
       $inputJSON = file_get_contents('php://input');
       $body = json_decode($inputJSON, TRUE); 
       print_r($input);
       print_r($body);
       print_r($inputJSON);
    // set inital headers
       $headers = [];
       $headers['Date'] = gmdate('D, d M Y H:i:s T');
       $headers['Content-Type'] = 'text/html; charset=utf-8';
       $headers['Server'] = $_SERVER['SERVER_NAME'];
       $lines = [];
       $lines[] = "HTTP/1.1 200 OK";
       // add the headers
       foreach ($headers as $key => $value) {
           $lines[] = $key . ": " . $value;
       }
       socket_write($spawn, implode("rn", $lines) . "rnrn" . $body) or die("Could not write outputn");
       socket_close($spawn);
    } while (true);
    // close sockets
    socket_close($socket);

我尝试了不同的方法来打印内容,但我只能打印出标题,这就是我在打印$input变量时得到的

     POST /test HTTP/1.1 Accept: application/json, application/xml, 
     text/json, text/x-json, text/javascript, text/xml User-Agent: 
     RestSharp/105.2.3.0 Content-Type: application/json Host: 
     192.168.8.102:454 Content-Length: 779 Accept-Encoding: gzip, 
     deflate

TCP以数据包的形式发送数据,并将它们重新组合回流中。这意味着,虽然您可以逐字节读取数据,而无需关心到达接收器的数据包的正确顺序,但仍可能发生一次调用socket_read()仅返回一个 IP 数据包的内容的情况。发送方可能将标头作为一个数据包发送,然后在一个或多个附加数据包中发送内容。

通常做的是在类似于下面的循环中调用接收函数:

$readTotal = 0;
while ($readTotal < $toRead) {
  $read = socket_read(...);
  if ($read === FALSE) {
    // error, cancel operation
  }
  $readTotal += $read;
}

在您的情况下,您必须从 Content-Length 字段中提取要读取的数量,如果您无法读取标头中承诺的字节数,则可能会在循环中设置超时。

最新更新