几乎所有 PHP 中的 TELNET 实现示例都使用套接字 (fsockopen)。这对我不起作用,因为它需要 Not Acceptable 时间(约 60 秒)。
我已经尝试将 fsockopen 用于其他目的,发现它比 cURL 慢。
问题 #1:为什么套接字这么慢?
更新:我发现我们需要设置 stream_set_timeout函数,我们可以控制套接字执行时间。我很好奇如何设置适当的超时或如何在收到响应后使其“停止等待”。
我无法使用 cURL 实现相同的功能。我应该将需要发送到 telnet 的命令放在哪里? CURLOPT_CUSTOMREQUEST 是正确的选择吗?我正在做这样的事情:
class TELNETcURL{
public $errno;
public $errstr;
private $curl_handle;
private $curl_options = array(
CURLOPT_URL => "telnet://XXX.XXX.XXX.XXX:<port>",
CURLOPT_TIMEOUT => 40,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HEADER => FALSE,
CURLOPT_PROTOCOLS => CURLPROTO_TELNET
);
function __construct(){
$this->curl_handle = curl_init();
curl_setopt_array($this->curl_handle, $this->curl_options);
}
public function exec_cmd($query) {
curl_setopt($this->curl_handle, CURLOPT_CUSTOMREQUEST, $query."\r\n");
$output = curl_exec($this->curl_handle);
return $output;
}
function __destruct(){
curl_close($this->curl_handle);
}
}
然后是类似这样的东西:
$telnet = new TELNETcURL();
print_r($telnet->exec_cmd("<TELNET commands go here>"));
我在 curl_exec 命令上收到“最长执行时间超过 30 秒”。
问题 #2:cURL 实现有什么问题?
最佳答案
您需要做的是使用非阻塞 IO,然后轮询响应。你现在正在做的是等待/挂起一个永远不会到来的响应——因此超时。
就我个人而言,我用 php 编写了很多套接字应用程序,它们工作得很好——我讨厌 cURL,因为它有错误、麻烦且非常不安全……只要阅读他们的错误列表,你就会感到震惊。
阅读 Excellent PHP 手册,其中包含许多关于如何执行 Polled IO 的示例,他们甚至为您提供了一个示例 telnet 服务器和客户端。
关于php - 在 PHP 中正确快速地进行 TELNET 的方法。套接字或 curl ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8411182/