5

我需要从 php 脚本发布消息,我可以很好地发布一条消息。但是现在我需要循环发布不同的消息,找不到正确的方法,这是我尝试过的:

$counter = 0;
$closure = function (\Thruway\ClientSession $session) use ($connection, &$counter) {
//$counter will be always 5
$session->publish('com.example.hello', ['Hello, world from PHP!!! '.$counter], [], ["acknowledge" => true])->then(
    function () use ($connection) {
        $connection->close(); //You must close the connection or this will hang
        echo "Publish Acknowledged!\n";
    },
        function ($error) {
        // publish failed
            echo "Publish Error {$error}\n";
        }
    );
};

while($counter<5){

    $connection->on('open', $closure);

    $counter++;
}
$connection->open();

在这里,我想向订阅者发布 $counter 值,但该值始终为 5, 1.有没有办法在循环之前打开连接,然后在循环中发布消息 2.如何访问 $session->publish() 从环形 ?

谢谢!

4

1 回答 1

5

有几种不同的方法可以实现这一点。最简单的:

$client = new \Thruway\Peer\Client('realm1');
$client->setAttemptRetry(false);
$client->addTransportProvider(new \Thruway\Transport\PawlTransportProvider('ws://127.0.0.1:9090'));

$client->on('open', function (\Thruway\ClientSession $clientSession) {
    for ($i = 0; $i < 5; $i++) {
        $clientSession->publish('com.example.hello', ['Hello #' . $i]);
    }
    $clientSession->close();
});

$client->start();

与路由器建立许多短连接并没有错。但是,如果您在守护进程中运行,那么设置仅使用相同客户端连接的东西然后使用反应循环而不是 while(1) 来管理循环可能会更有意义:

$loop = \React\EventLoop\Factory::create();

$client = new \Thruway\Peer\Client('realm1', $loop);
$client->addTransportProvider(new \Thruway\Transport\PawlTransportProvider('ws://127.0.0.1:9090'));

$loop->addPeriodicTimer(0.5, function () use ($client) {

    // The other stuff you want to do every half second goes here

    $session = $client->getSession();

    if ($session && ($session->getState() == \Thruway\ClientSession::STATE_UP)) {
        $session->publish('com.example.hello', ['Hello again']);
    }
});

$client->start();

请注意,$loop 现在被传递到客户端构造函数中,并且我摆脱了禁用自动重新连接的行(因此,如果存在网络问题,您的脚本将重新连接)。

于 2015-07-13T18:47:19.640 回答