我需要从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();这里我想发布会话的值给订阅者,但值始终是5,1。有没有办法在循环之前打开连接,然后在循环中发布消息?2.如何从循环访问$ $counter -> publish ()?
谢谢!
发布于 2015-07-14 02:47:20
有几种不同的方法可以实现这一点。最简单的是:
$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现在被传递到客户端构造函数中,而且我去掉了禁用自动重新连接这一行(因此,如果出现网络问题,您的脚本将重新连接)。
https://stackoverflow.com/questions/31378079
复制相似问题