我是reactphp的新手。我涉猎node.js.我正在研究一个项目,该项目要求在特定时间触发事件并发布给订阅的客户。这是EventLoop适合的东西吗?我怎么能接近这个方向?
答案 0 :(得分:2)
您使用React EventLoop的假设是正确的。您可以使用定期计时器来触发发送消息。既然你提到了Ratchet并发布了+ subscribe,那么我假设你是在使用WAMP over WebSockets做的。这是一些示例代码:
<?php
use Ratchet\ConnectionInterface;
class MyApp implements \Ratchet\Wamp\WampServerInterface {
protected $subscribedTopics = array();
public function onSubscribe(ConnectionInterface $conn, $topic) {
// When a visitor subscribes to a topic link the Topic object in a lookup array
if (!array_key_exists($topic->getId(), $this->subscribedTopics)) {
$this->subscribedTopics[$topic->getId()] = $topic;
}
}
public function onUnSubscribe(ConnectionInterface $conn, $topic) {}
public function onOpen(ConnectionInterface $conn) {}
public function onClose(ConnectionInterface $conn) {}
public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {}
public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {}
public function onError(ConnectionInterface $conn, \Exception $e) {}
public function doMyBroadcast($topic, $msg) {
if (array_key_exists($topic, $this->subscribedTopics)) {
$this->subscribedTopics[$topic]->broadcast($msg);
}
}
}
$myApp = new MyApp;
$loop = \React\EventLoop\Factory::create();
$app = new \Ratchet\App('localhost', 8080, '127.0.0.1', $loop);
$app->route('/my-endpoint', $myApp);
// Every 5 seconds send "Hello subscribers!" to everyone subscribed to the "theTopicToSendTo" topic/channel
$loop->addPeriodicTimer(5, function($timer) use ($myApp) {
$myApp->doMyBroadcast('theTopicToSendTo', 'Hello subscribers!');
});
$app->run();