简体   繁体   中英

PHP socket connection optimization

I am making this connection with an API that uses telnet, when I run the commands in a shell everything happens faster, however, when I run the commands using php sockets performance drops dramatically. I'm having some code misconceived?

/ **  
* 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;  
}

Because your code is connecting and authenticating (logging-in) yourself everytime a command is issued. So, there are more communications between client and server than in a single SSH session.

Solution: Try pfsockopen instead of fsockopen and don't authenticate everytime. It behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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