在预定的时间发布到订阅的客户使用reachphp或ratchet

问题描述:

我是新来的reactphp。我涉足node.js.我正在研究一个项目,要求事件在特定时间触发并发布给订阅的客户端。这是EventLoop适合的东西吗?我可以如何处理这个问题的任何方向?在预定的时间发布到订阅的客户使用reachphp或ratchet

您对使用React EventLoop的假设是正确的。您可以使用定期计时器来触发发送消息。既然你提到了Ratchet并发布了+订阅,我会假设你正在使用WAMP而不是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(); 
+0

如果客户端发布到某个主题如何将数据导入到onPublish()方法中?我使用的是authobhan js – ravisoni

+0

conn.publish('kittensCategory',['Hello,world!']);我怎么能在服务器上的onPublish方法中获得hello world – ravisoni