gpt4 book ai didi

php - PHP套接字连接优化

转载 作者:行者123 更新时间:2023-12-03 17:19:01 25 4
gpt4 key购买 nike

我正在使用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 session 中的通信更多。

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

关于php - PHP套接字连接优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com