繁体   English   中英

PHP套接字连接优化

[英]PHP socket connection optimization

我正在使用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;  
}

因为您的代码在每次发出命令时都会连接并进行身份验证(登录)。 因此,客户端和服务器之间的通信比单个SSH会话中的通信更多。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM