通过 Phalcon\Async 我们可以异步调用方法。
<?php
// 默认使用 Phalcon 源码文件路径
Phalcon\Async::setFilename('/tmp');
$id1 = Phalcon\Async::call(function () {
return 'one1';
});
$id2 = Phalcon\Async::call(function () {
return 'one2';
});
<?php
$num = Phalcon\Async::count();
<?php
$ret = Phalcon\Async::recv($id1);
$rets = Phalcon\Async::recvAll();
<?php
$task = Phalcon\Async\Task::async(function () {
return 1;
});
$v = Phalcon\Async\Task::await($task);
<?php
$builder = new Phalcon\Async\ProcessBuilder(PHP_BINARY);
$builder = $builder->withStdoutPipe();
$builder->withStderrInherited();
$proc = $builder->start(__DIR__.'/process.php');
if ($proc->isRunning()) {
echo "Running".PHP_EOL;
$stdout = $proc->getStdout();
try {
if (null !== ($chunk = $stdout->read())) {
echo $chunk;
}
} finally {
$stdout->close();
}
}
服务器端监听:
<?php
$server = Phalcon\Async\Network\TcpServer::listen('localhost', 8080);
try {
var_dump($server->getAddress(), $server->getPort());
while (true) {
$socket = $server->accept();
if ($socket === false) {
continue;
}
Phalcon\Async\Task::async(function () use ($socket) {
try {
$chunk = $socket->read();
if (empty($chunk)) {
$socket->close();
return;
}
$sendchunk = 'Hello World';
$sendchunk = \sprintf("HTTP/1.1 200 OK\r\nServer: webserver\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n%x\r\n%s\r\n0\r\n\r\n", \strlen($sendchunk), $sendchunk);
$socket->write($sendchunk);
} catch (\Throwable $e) {
echo $e, "\n\n";
} finally {
$socket->close();
}
});
}
} finally {
$server->close();
}
客户端连接:
<?php
$socket = TcpSocket::connect('localhost', 80);
try {
$socket->writeAsync("GET /json HTTP/1.0\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n")
while (null !== ($chunk = $socket->read())) {
var_dump($chunk);
}
} finally {
$socket->close();
}
WebSocket 服务端 <https://github.com/dreamsxin/cphalcon7/blob/master/examples/async/websocket-server.php>`_:
<?php
// ...
$ws = new Websocket('0.0.0.0', 10001, function($socket, $headers, $path, $data) {
var_dump($data);
Websocket::sendFragment($socket, 'Re: '.$data);
});
$ws->start();
WebSocket 客户端 <https://github.com/dreamsxin/cphalcon7/blob/master/examples/async/websocket-client.php>`_:
php -d extension=phalcon.so websocket-client.php -c ws://localhost:10001