我试图用reactphp做长轮询。
我有一个函数getNotifications,它停留在长时间的投票中,等待来自电报的响应。
此电报api可以将请求保持为打开状态,直到超时,或者在之前发送响应(如果有通知,则在50秒结束时)。
在电报回复后,我怎么能回忆起getNotifications?基本上,我希望在有响应时再次调用getNotifications。
这是我的密码
谢谢大家
<?php
require "vendor/autoload.php";
use Clue\React\Buzz\Browser;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\LoopInterface;
$loop = React\EventLoop\Factory::create();
$browser = new Browser($loop);
$method = "getUpdates";
$timeout = 50;
$params = [
"offset" => 550495530,
"limit" => 1000,
"timeout" => $timeout
];
$bot_key = "your bot token";
$query = http_build_query($params);
$url = "https://api.telegram.org/bot" . $bot_key . "/" . $method . "?" . $query;
$browser = $browser->withOptions(array(
'timeout' => $timeout
));
function callback(){
echo "done";
}
function getNotifications($url, $browser, LoopInterface $loop){
$browser->get($url)->then(function (ResponseInterface $response) {
// response received within 50 seconds. Telegram longpolling
var_dump((string)$response->getBody());
callback();
});
}
function timer($start, LoopInterface $loop)
{
//Timer only used to count seconds
$loop->addPeriodicTimer(1.0, function ($timer) use (&$start, $loop) {
echo "tick ". $start++ . "\n";
});
}
timer(0, $loop);
getNotifications($url, $browser, $loop);
$loop->run();发布于 2020-03-26 19:32:30
好的,我找到解决办法了。要将参数传递给匿名函数,我需要使用使用关键字。然后,在函数内部,我可以正确地访问变量。
function getNotifications($url, $browser, LoopInterface $loop){
$browser->get($url)->then(function (ResponseInterface $response) use ($url, $browser,$loop) {
// response received within 50 seconds. Telegram longpolling
var_dump((string)$response->getBody());
callback();
getNotifications($url, $browser,$loop);
});}
https://stackoverflow.com/questions/60870996
复制相似问题