112*_*233 10 php ratchet rethinkdb
我想运行一个迭代生成器类的函数.只要Ratchet连接处于活动状态,发电机功能就会运行.我需要做的就是在run执行方法后实现这一点:
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/xxx/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8180,
'0.0.0.0'
);
$server->run();
Run Code Online (Sandbox Code Playgroud)
这是我在服务器启动后需要运行的方法:
function generatorFunction()
{
$products = r\table("tableOne")->changes()->run($conn);
foreach ($products as $product) {
yield $product['new_val'];
}
}
Run Code Online (Sandbox Code Playgroud)
以前我之前正在调用这个函数$server->run():
for ( $gen = generatorFunction(); $gen->valid(); $gen->next()) {
var_dump($gen->current());
}
$server->run();
Run Code Online (Sandbox Code Playgroud)
但这不允许客户端建立与Ratchet服务器的连接.我怀疑它永远不会$server->run()被生成,因为生成器类正在被迭代.
所以现在,我想首先启动服务器,然后调用这个生成器方法,以便它可以继续监听更改rethinkdb.
我怎么做?
让我们从例子开始:
<?php
require 'vendor/autoload.php';
class Chat implements \Ratchet\MessageComponentInterface {
function onOpen(\Ratchet\ConnectionInterface $conn) { echo "connected.\n"; }
function onClose(\Ratchet\ConnectionInterface $conn) {}
function onError(\Ratchet\ConnectionInterface $conn, \Exception $e) {}
function onMessage(\Ratchet\ConnectionInterface $from, $msg) {}
}
$loop = \React\EventLoop\Factory::create(); // create EventLoop best for given environment
$socket = new \React\Socket\Server('0.0.0.0:8180', $loop); // make a new socket to listen to (don't forget to change 'address:port' string)
$server = new \Ratchet\Server\IoServer(
/* same things that go into IoServer::factory */
new \Ratchet\Http\HttpServer(
new \Ratchet\WebSocket\WsServer(
new Chat() // dummy chat to test things out
)
),
/* our socket and loop objects */
$socket,
$loop
);
$loop->addPeriodicTimer(1, function (\React\EventLoop\Timer\Timer $timer) {
echo "echo from timer!\n";
});
$server->run();
Run Code Online (Sandbox Code Playgroud)
为了实现您所需要的,您不必在之前或之后运行循环,$server->run()但需要同时运行。
为此,您需要比 Ratchet 更深入地了解 ReactPHP 及其EventLoop。如果您有权访问循环接口,那么添加计时器(执行一次)或周期性计时器(每 n 秒)就是小菜一碟。
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |