我想阅读一个长期运行的php进程,该进程将在满足条件时返回数据。
从我的研究中,我发现了:
我正在努力理解&应用我的问题的实现。我在PHP中有以下循环:
public function store(ClientImpl $a)
{
$request = \Illuminate\Support\Facades\Request::all();
$originateMsg = new OriginateAction('Local/' . $request['agent'] . '@auto-answer');
$originateMsg->setContext('G-Outgoing');
$originateMsg->setPriority('1');
$originateMsg->setExtension($request['dial']);
$a->send($originateMsg);
while(true) {
if( $a->process() ) break;
usleep(1000);
}
$a->close();
echo 'OK';
ob_end_flush();
flush();
}
$a->process()
调用以下方法:
/**
* Main processing loop. Also called from send(), you should call this in
* your own application in order to continue reading events and responses
* from ami.
*/
public function process()
{
$msgs = $this->getMessages();
foreach ($msgs as $aMsg) {
if ($this->_logger->isDebugEnabled()) {
$this->_logger->debug(
'------ Received: ------ ' . "\n" . $aMsg . "\n\n"
);
}
$resPos = strpos($aMsg, 'Response:');
$evePos = strpos($aMsg, 'Event:');
if (($resPos !== false) && (($resPos < $evePos) || $evePos === false)) {
$response = $this->_messageToResponse($aMsg);
$this->_incomingQueue[$response->getActionId()] = $response;
} else if ($evePos !== false) {
$event = $this->_messageToEvent($aMsg);
$response = $this->findResponse($event);
if ($response === false || $response->isComplete()) {
$this->dispatch($event);
} else {
$response->addEvent($event);
}
} else {
// broken ami.. sending a response with events without
// Event and ActionId
$bMsg = 'Event: ResponseEvent' . "\r\n";
$bMsg .= 'ActionId: ' . $this->_lastActionId . "\r\n" . $aMsg;
$event = $this->_messageToEvent($bMsg);
$response = $this->findResponse($event);
$response->addEvent($event);
}
if ($this->_logger->isDebugEnabled()) {
$this->_logger->debug('----------------');
}
}
}
$a->process()
然后堆叠事件消息,为了阅读这些消息,我创建了IEventListener
的实现,在调用$a->process()
时也称为“幕后”。
class VoipEventStart implements IEventListener
{
public function handle(EventMessage $event)
{
$a = $event->getKeys();
if( ($a['event'] == "Hangup" || $a['event'] == "HangupRequest") && strpos($a['channel'], 'SIP/') !== FALSE)
{
return true;
}
return false;
}
}
当用户处于活动呼叫时,处理方法从Asterisk PBX系统读取事件。这意味着只要通话持续,过程循环就会持续。
如果浏览器没有加载/等待,我将如何执行此客户端?
答案 0 :(得分:0)
您可以使用Server Sent Events或某些套接字实现,但最简单的可能是长轮询策略可以很好地运行。
为此,从客户端发送一个普通的AJAX请求,并使服务器仅在满足条件时返回。它可以像更改服务器端代码一样简单:
while(true) {
if( $a->process() ) break;
usleep(1000);
}
echo 'OK';
ob_end_flush();
flush();
客户端应该向启动上述循环的PHP文件发送一个简单的GET请求。这样,当响应返回到此请求时,您知道process()返回true。
客户端代码可能如下所示:
<div>Call status: <span id="status">In call</span></div>
<script>
$.get('/check_call_status.php?callerId=123', function(response) {
if(response === 'OK') {
$('#staus').html('finished');
}
});
</script>
当然,处理超时可能会更复杂。例如。如果在给定时间段内对长轮询请求没有响应,请重新启动它 - 即中止请求并再次发送以避免客户端或服务器超时。