2012-04-10 136 views
1

我正在使用fsockopen和fwrite發送和接收數據。我的應用程序收到正確的響應,但似乎要等到某種超時後再繼續。我懷疑在完成接收響應之後,我沒有正確關閉連接,這說明了等待。有人可以看看我的代碼嗎?收到數據後關閉HTTP連接

private static function Send($URL, $Data) { 
      $server = parse_url($URL, PHP_URL_HOST); 
      $port = parse_url($URL, PHP_URL_PORT); 

      // If the parsing the port information fails, we will assume it's on a default port. 
      // As such, we'll set the port in the switch below. 
      if($port == null) { 
       switch(parse_url($URL, PHP_URL_SCHEME)) { 
        case "HTTP": 
         $port = 80; 
         break; 
        case "HTTPS": 
         $port = 443; 
         break; 

       } 
      } 

      // Check if we are using a proxy (debug configuration typically). 
      if(\HTTP\HTTPRequests::ProxyEnabled) { 
       $server = \HTTP\HTTPRequests::ProxyServer; 
       $port = \HTTP\HTTPRequests::ProxyPort; 
      } 

      // Open a connection to the server. 
      $connection = fsockopen($server, $port, $errno, $errstr); 
      if (!$connection) { 
       die("OMG Ponies!"); 
      } 

      fwrite($connection, $Data); 

      $response = ""; 
      while (!feof($connection)) { 
       $response .= fgets($connection); 
      } 
      fclose($connection); 

      return $response; 
     } 
+0

您是否嘗試使用'timeout'值? http://us2.php.net/manual/en/function.fsockopen.php – 2012-04-10 23:37:33

+0

不知道這是否有幫助,但看看http://php.net/manual/en/function.feof頂部的註釋.php標題下的「警告:如果由fsockopen()打開的連接未被服務器關閉,則feof()將掛起。要解決此問題,請參閱下面的示例」 – 2012-04-10 23:44:07

+0

@BenLee Hmm。修改似乎沒有工作。仍然需要30秒超時。 – user978122 2012-04-11 02:39:39

回答

1

問題是與這一行:

while (!feof($connection)) { 

套接字是流;除非另一方關閉連接第一個feof將永遠不會返回true並且您的腳本最終會超時。

要執行有序關閉,雙方必須關閉連接的結束; 其中一個可以作爲對另一方的迴應,但很明顯,如果兩方都在等待另一方首先關閉,那麼沒有人會這樣做。

輸出內容後,對方的程序是否關閉連接?看起來不是。

+0

我現在解析標題以獲取內容長度,並使用它來確定何時嚴重連接。 – user978122 2012-04-21 00:03:20

+0

@ user978122:如果你能把它拉下來(這意味着,如果服務器發送內容的長度),這是一個好方法。乾杯! – Jon 2012-04-21 18:32:06