2010-12-27 15 views
2

シェルでコマンドを実行すると、telnetを使用するAPIでこの接続を行いますが、PHPソケットのパフォーマンスを大幅に下げてコマンドを実行すると、すべてが速くなります。私はいくつかのコードを誤解していますか?PHPソケット接続の最適化

/ ** 
* Tries to make the connection to the server specified in the constructor, if the connection is made returns TRUE 
* Otherwise FALSE. 
* @Return boolean 
*/ 
public function connect() { 

    try { 
     $stream = fsockopen($this->getHost(), $this->getPort(), $errno, $errstr, $this->getTimeOut()); 

     $this->setStream($stream); 

     return true; 
    } catch (ErrorException $e) { 
     echo $e->getMessage(); 
     return false; 
    } catch (Exception $e) { 
     echo $e->getMessage(); 
     return false; 
    } 
} 

/** 
* Runs the specified command in $command at voipzilla's API through a socket connection. 
* @See $this-> connect() 
* @Param string $command 
* @Param int $nl number of new lines (Enter) after the command 
* @Param boolean $command Sets the command clause will be added to the specified command 
* @Return string coming API's response API 
*/ 
public function runCommand($command, $nl=4, $commandClause=true) { 
     //response 
     $response = null; 
     // 
     $login = "login " . $this->getLogin() . "\n"; 
     $login .= "password " . $this->getPassword() . "\n\n"; 

     if ($commandClause) { 
      $command = "command " . $command; 
     } 

     $command = $login . $command; 

     for ($i = 1; $i <= $nl; $i++) { 
      $command .= "\n"; 
     } 

     if(!$this->connect()){exit(0);} 

     fwrite($this->getStream(), $command); 

     while (!feof($this->getStream())) { 
      $response .= fgets($this->getStream(), 128); 
     } 

     return $response; 
} 

答えて

4

あなたのコードは、接続して認証しているので(ログイン)自分毎回コマンドが発行されます。したがって、単一のSSHセッションよりもクライアントとサーバーの間の通信量が増えます。

解決策:fsockopenの代わりにpfsockopenを試してください。毎回認証しないでください。 fsockopen()とまったく同じように動作しますが、スクリプトの終了後に接続が閉じられないという違いがあります。それはfsockopen()の永続的なバージョンです。

+0

私は一度だけ認証しようとしました。認証後にコマンドを実行しようとすると、APIが自動的に接続を終了するため、コマンドは実行されません。認証と実行の間隔次のコマンド(それは遅いために長いです)。私が今やっているやり方(毎回の認証)はうまくいきます。私はpfsockopenを使いましたが、遅さは続きます。 –