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()
.
精彩评论