PHP套接字连接优化

时间:2010-12-27 13:31:15

标签: php sockets optimization networking telnet

我正在使用一个使用telnet的API建立此连接,当我在shell中运行命令时,一切都发生得更快,但是,当我使用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;  
}

1 个答案:

答案 0 :(得分:4)

因为您的代码是自己连接和验证(登录)每次,所以发出命令。因此,客户端和服务器之间的通信比单个SSH会话中的通信更多。

解决方案:尝试pfsockopen而不是fsockopen,并且不会每次都进行身份验证。它的行为与fsockopen()完全相同,不同之处在于脚本完成后连接未关闭。它是fsockopen()的持久版本。