【问题标题】:fsockopen & Close connection in PHP but keep executing scriptPHP中的fsockopen和关闭连接但继续执行脚本
【发布时间】:2011-04-06 08:26:20
【问题描述】:

我有一个 PHP 脚本需要在返回数据后关闭连接,但继续执行:

<?php
  // Some code

  ob_start();

  echo $data;

  header("Content-type: application/soap+xml;charset=UTF-8\r\n");
  header("Content-Length: " . ob_get_length() . "\r\n");
  header("Content-Encoding: none\r\n");
  header("Connection: close\r\n\r\n");

  // Print buffer
  ob_end_flush();
  ob_flush();
  flush();

  // Close connection

  // Some code, continue executing
?>

它适用于某些客户端,但有时我需要使用其他 PHP 脚本调用

<?php
    // Some code

    $connection = @fsockopen($url['host'], $url['port'], $errno, $errstr);

    if (!$connection) { 
      throw new Exception('');
    }

    fputs($connection, "POST {$url['path']} HTTP/1.1\r\n");
    fputs($connection, "Host: {$url['host']}\r\n");
    fputs($connection, "Content-type: text/xml;charset=UTF-8\r\n");
    fputs($connection, "SOAPAction: \"{$soapaction}\"\r\n");
    fputs($connection, "Content-Length: " . strlen($request) . "\r\n");
    fputs($connection, "Content-Encoding: none\r\n");
    fputs($connection, "Connection: close\r\n\r\n");
    fputs($connection, $request);

    $respponse = '';
    while(!feof($connection)) {
      // receive the results of the request
      $response .= fgets($connection, 512);
    }

    // some code
?>

问题是:fsockopen 接收数据时不会关闭连接,只有在所有第一个脚本结束时。

我唯一的想法,就是在收到数据时检查长度并关闭手册。

【问题讨论】:

    标签: php http soap http-headers buffer


    【解决方案1】:

    您的第一个(服务器)脚本将保持套接字打开,直到它终止。 套接字比 HTTP 级别低,当您发送 Connection: close 标头时,您的第二个(客户端)脚本应该自己处理它,而不是 fsockopen 函数。

    做你做的事(计算响应的字节数)是处理它的正确方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      相关资源
      最近更新 更多