编程语言
首页 > 编程语言> > php – voryx thruway多次发布

php – voryx thruway多次发布

作者:互联网

我需要从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()?

谢谢!

解决方法:

有几种不同的方法可以实现这一目标.最简单的:

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

与路由器建立许多短连接没有任何问题.如果你在一个守护进程中运行,那么设置一些只使用相同客户端连接的东西然后使用react循环来管理循环而不是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现在被传递到客户端构造函数中,并且我还没有禁用自动重新连接的行(因此,如果存在网络问题,您的脚本将重新连接).

标签:php,wamp-protocol,thruway
来源: https://codeday.me/bug/20190519/1137119.html