所以,我想在 PHP 中创建一个异步 Web 服务。为什么?因为我有一个不错的异步前端,但如果我有超过 6 个活动 TCP 连接,Chrome 会阻止我的请求。当然,我读过一些类似的问题,例如:
但这些不包括我的问题。
我安装pthreads
的目的是让我能够在不同的线程中发出多个请求,这样我的 PHP 就不会阻塞其他请求(在我的情况下,我开始了一个长进程,如果进程是,我希望能够轮询是否仍然忙碌)。
PHPReact 似乎是一个不错的库(非阻塞 I/O,异步),但这也不起作用(仍然同步)。
我是否遗漏了什么,或者现在这在 PHP 中仍然是不可能的?
class Example{
private $url;
function __construct($url){
$this->url = $url;
echo 'pooooof request to ' . $this->url . ' sent <br />';
$request = new Request($this->url);
$request->start();
}
}
class Request extends Thread{
private $url;
function __construct($url){
$this->url = $url;
}
function run(){
// execute curl, multi_curl, file_get_contents but every request is sync
}
}
new Example('https://gtmetrix.com/why-is-my-page-slow.html');
new Example('http://php.net/manual/en/function.file-get-contents.php');
new Example('https://www.google.nl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=php%20file%20get%20contents');
理想的情况是使用回调。
附言。我见过一些提供此功能的服务器(如 Node.js),但我更喜欢本机方法。当这不可能时,我真的在考虑切换到 Python、Java、Scala 或其他支持异步的语言。