Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

voryx thruway multiple publish

I need to publish messages from php script, I can publish a single message fine. But now I need to publish different messages in loop, can't find proper way how to do it, here is what I tried:

$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();

Here I want to publish $counter value to subscribers but the value is always 5, 1.Is there a way that I open connection before loop and then in loop I publish messages 2.How to access to $session->publish() from loop ?

Thanks!

like image 839
dave101ua Avatar asked Jul 13 '15 07:07

dave101ua


1 Answers

There are a couple different ways to accomplish this. Most simply:

$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();

There is nothing wrong with making many short connections to the router. If you are running in a daemon process though, it would probably make more sense to setup something that just uses the same client connection and then use the react loop to manage the loop instead of 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();

Notice that the $loop is now being passed into the client constructor and also that I got rid of the line disabling automatic reconnect (so if there are network issues, your script will reconnect).

like image 131
mbonneau Avatar answered Oct 03 '22 23:10

mbonneau