0

我是 reactphp 新手。我涉足 node.js。我正在研究一个需要在特定时间触发事件并将其发布给订阅客户的项目。这是 EventLoop 适合的东西吗?关于我如何解决这个问题的任何方向?

4

1 回答 1

2

您使用 React EventLoop 的假设是正确的。您可以使用周期性计时器来触发发送消息。既然您提到了 Ratchet 和发布+订阅,我将假设您使用 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();
于 2014-05-18T14:29:45.410 回答